iOS-swift-協議和拓展
阿新 • • 發佈:2017-06-18
desc rop turn ted ext 註意 color int ret 1 協議(
2 拓展(
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-協議和拓展