1

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?

mfaani
  • 33,269
  • 19
  • 164
  • 293
SwiftyJD
  • 5,257
  • 7
  • 41
  • 92

2 Answers2

3

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.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • well why not just extend UIView? I mean we are actually eventually extending UIView right? – mfaani Jan 14 '17 at 03:18
  • @Honey That is a nice question but it isn't what the OP asked. Please don't change the subject. – matt Jan 14 '17 at 03:25
  • I follow up to my question can be found [here](http://stackoverflow.com/questions/41706504/why-should-not-directly-extend-uiview-or-uiviewcontroller) – mfaani Jan 17 '17 at 21:14
0

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

renjithr
  • 313
  • 4
  • 12