What's the reason to add functions to a protocol via an extension, why not just put it in the definition of the protocol itself?

前提是你 提交于 2019-12-11 06:18:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!