上QQ阅读APP看书,第一时间看更新
Protocol extensions
With protocol extensions, it is possible to provide an implementation for the required methods, without letting the conforming types provide that implementation.
We have updated the Toggling protocol with an additional required member: isActive. With the protocol extension, we can declare a default implementation for our types, Bool and State. We can also provide a default implementation for any other type that would choose to conform to the Toggling protocol:
protocol Toggling {
mutating func toggle()
var isActive: Bool { get }
}
extension Toggling where Self == Bool {
var isActive: Bool {
return self
}
}
extension Toggling where Self == State {
var isActive: Bool {
return self == .on
}
}