2017-01-14 38 views
1

我一直想知道为什么当我看到协议的例子时,人们倾向于通过扩展添加大部分功能。像这样:通过扩展为协议添加功能的原因是什么,为什么不把它放在协议本身的定义中呢?

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

扩展的背后是什么?为什么不把它包含在最初的协议定义中呢?

回答

3

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

因为这是不合法的。一个协议可能包含一个函数声明,但不包括函数体(实现)。协议扩展是关于包含默认实现的。这就是协议扩展

+0

以及为什么不延长的UIView编码?我的意思是我们实际上最终扩展UIView的权利? – Honey

+0

@Honey这是一个很好的问题,但这不是OP要求的。请不要改变主题。 – matt

+0

我跟着我的问题可以发现[这里](http://stackoverflow.com/questions/41706504/why-should-not-directly-extend-uiview-or-uiviewcontroller) – Honey

0

像马特解释说,这是协议应该如何工作。除此之外,协议扩展启用了全新的编程方式。它叫Protocol oriented programming

随着语言Java,.NET目标C,你不能有多重继承。您应该从一个类继承并保留其他协议。这意味着具体方法可以从一个地方继承。但通过课程扩展,您也可以拥有这些功能。

已经看清楚了​​3210

快乐与POP