通过扩展将function添加到协议的原因是什么,为什么不把它放在协议本身的定义中呢?

我一直想知道为什么当我看到协议的例子时,人们倾向于通过扩展添加大部分function。 喜欢这个:

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) } } } } 

扩展背后有什么意义? 为什么不将它包含在初始协议定义中?

为什么不将它包含在初始协议定义中

因为那不合法。 协议可以包括函数声明但不包括函数体(实现)。 协议扩展包括默认实现。 这就是协议扩展。

就像亚特解释的那样,那就是协议应该如何运作。 除了协议扩展启用了一种全新的编程方式。 它称为面向协议的编程

使用Languages Java,.Net Objective C,您无法实现多重inheritance。 您应该从一个类inheritance并从协议中inheritance。 这意味着可以从一个地方inheritance具体方法。 但是对于类扩展,你也可以拥有它。

看看Swift 3中面向协议的编程

用POP快乐编码