上QQ阅读APP看书,第一时间看更新
Protocol extensions
Protocol extensions allow us to define behavior on protocols rather than in each type's inpidual conformance or global function. By creating an extension on a protocol, all conforming types automatically gain this method implementation without any additional modification. We can specify constraints that conforming types must satisfy before the methods and properties of the extensions are available when we define a protocol extension. For instance, we can extend our ExampleProtocol to provide default functionality as follows:
extension ExampleProtocol {
var simpleDescription: String {
get {
return "The description is: \(self)"
}
set {
self.simpleDescription = newValue
}
}
mutating func adjust() {
self.simpleDescription = "adjusted simple description"
}
}