2017-01-14 35 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