标签:
1.协议
Swift使用protocol定义协议:
protocol ExampleProtocol { var simpleDescription: String { get } mutating func adjust() }
类型、枚举和结构都可以实现协议:
class SimpleClass: ExampleProtocol { var simpleDescription: String = "A very simple class." var anotherProperty: Int = 69105 func adjust() { simpleDescription += " Now 100% adjusted." } } var a = SimpleClass() a.adjust() let aDescription = a.simpleDescription struct SimpleStructure: ExampleProtocol { var simpleDescription: String = "A simple structure" mutating func adjust() { simpleDescription += " (adjusted)" } } var b = SimpleStructure() b.adjust() let bDescription = b.simpleDescription
2.扩展
扩展用于在已有的类型上增加新的功能(比如新的方法或属性),Swift使用extension声明扩展:
extension Int: ExampleProtocol { var simpleDescription: String { return "The number \(self)" } mutating func adjust() { self += 42 } } 7.simpleDescription
Swift学习5---协议(protocol)和扩展(extension)
标签:
原文地址:http://www.cnblogs.com/ShawnLi/p/4502184.html