扩展就是向一个已有的类、结构体或枚举类型添加新功能(functionality)
扩展可以
语法
extension SomeType { // 加到SomeType的新功能写到这里 } extension SomeType: SomeProtocol,AnotherProctocol { // 协议实现写到这里 }
范例
extension String { subscript (range: Range<Int>) -> String { get { let startIndex = advance(self.startIndex,range.startIndex) let endIndex = advance(startIndex,range.endIndex - range.startIndex) return self[Range(start: startIndex,end: endIndex)] } } subscript (start:Int,length:Int) -> String { get { let startIndex = advance(self.startIndex,start) let endIndex = advance(startIndex,length) return self[Range(start: startIndex,end: endIndex)] } } var Length : Int{ get{ return count(self) } } } println("ABCDEFGHI"[0...4]) //ABCDE println("ABCDEFGHI"[0..<4]) //ABCD println("ABCDEFGHI"[1,4]) //BCDE println("ABCDEFGHI".Length) //9