標籤:turn esc self int 存在 類型 結構 imp ext
1 協議(
protocol)
使用關鍵字 protocol 建立協議。
protocol ExampleProtocol { var simpleDescription: String { get } mutating func adjust() }
類、枚舉和結構體都支援協議。
lass 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
注意關鍵字 mutating,在結構體 SimpleStructure 中使用 mutating 實現協議中的方法。而在類中 SimpleClass,卻不需要關鍵字 mutating 實現協議方法,因為類中方法本身就不需要關鍵字mutating 聲明。
2 拓展(
extension)
使用關鍵字 extension 建立一個已存在類型的拓展。
extension Int: ExampleProtocol { var simpleDescription: String { return "The number \(self)" } mutating func adjust() { self += 42 } } print(7.simpleDescription)
恩,努力。
iOS-swift-協議和拓展