问题
I've always wondered why when I see examples of protocols people tend to add most of the functions via an extension. Like this:
protocol Flashable {}//Can be empty becuase function is in extension
extension Flashable where Self: UIView //Makes this protocol work ONLY if object conforms to UIView (ie. uilable, uibutton, etc.)
{
func flash() {
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn, animations: {
self.alpha = 1.0 //Object fades in
}) { (animationComplete) in
if animationComplete == true {
UIView.animate(withDuration: 0.3, delay: 2.0, options: .curveEaseOut, animations: {
self.alpha = 0.0 //Object fades out
}, completion: nil)
}
}
}
}
What's the point behind the extension? why not just include it in the initial protocol definition?
回答1:
why not just include it in the initial protocol definition
Because that's not legal. A protocol may include a function declaration but not the function body (the implementation). A protocol extension is about including a default implementation. That's what a protocol extension is.
回答2:
Like matt explained, thats how Protocols should work. Other than that Protocol extensions enabled a totally new way of programming. Its called Protocol oriented programming
With Languages Java, .Net Objective C, You cant have multiple inheritance. You should Inherit from one class and remaining from protocols. That means concrete methods can be inherited from one place. But with class extensions you can have that too.
Have look at Protocol-Oriented Programming in Swift 3
Happy coding with POP
来源:https://stackoverflow.com/questions/41646367/whats-the-reason-to-add-functions-to-a-protocol-via-an-extension-why-not-just