Swift - Protocols and Extensions
The Swift Programming Language中的代码加上部分EXPERIMENT
import UIKit 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 enum SimpleEnum: ExampleProtocol { case SIMPLE(String) var simpleDescription: String { get { switch self { case let .SIMPLE(str): return str } } } mutating func adjust() { switch self { case let .SIMPLE(str): self = .SIMPLE(str + " (adjusted)") } } } var c = SimpleEnum.SIMPLE("A simple enum") c.simpleDescription c.adjust() c.simpleDescription extension Int: ExampleProtocol { var simpleDescription: String { return "The number \(self)" } mutating func adjust() { self += 42 } } var d = 7 d.simpleDescription d.adjust() let protocolValue: ExampleProtocol = a protocolValue.simpleDescription
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。