extension SomeType { // }扩展使其符合某个协议
extension SomeType: SomeProtocol, AnotherProctocol { // 协议实现写到这里 }协议这部分后会后续讲解
extension String { //扩展下标脚本 subscript (r: Range<Int>) -> String { get { let subStart = advance(self.startIndex, r.startIndex, self.endIndex) let subEnd = advance(subStart, r.endIndex - r.startIndex, self.endIndex) return self.substringWithRange(Range(start: subStart, end: subEnd)) } } //扩展实例方法 func substring(#from: Int) -> String { let end = countElements(self) return self[from..<end] } func substring(#from: Int, length: Int) -> String { let end = from + length return self[from..<end] } func substring(#from:Int, to:Int) ->String { return self[from..<to] } //定义新的构造器 init(first:String,second:String) { self.init(first+second) } //定义新的嵌套类型,这里的嵌套类型是一个枚举 //所谓嵌套类型,简单理解就是在一个类型里定义另一个类型 enum Kind{ case IsIntStr,NotIntStr } //定义一个新的实例变量,返回这个字符串是否是可以转换为Int var kind:Kind{ var result:Kind = Kind.IsIntStr if self.toInt()? == nil{ result = .NotIntStr } return result } } var str = String(first:"hello ",second:"hwc") var str1 = str.substring(from:6) //hwc var str2 = str.substring(from:0,to:5) //hello var str3 = str.substring(from:0,length:5)//hello var str4 = str[0...5] //hello var strKind = str.kind //NotIntStr if strKind == String.Kind.NotIntStr{ println("Not an int string") }备注:想看下结果的同学直接把这段代码拷贝到palyground中就能看到结果
原文地址:http://blog.csdn.net/hello_hwc/article/details/41555225