標籤:
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.simpleDescriptionstruct 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)