我一直想知道爲什麼當我看到協議的例子時,人們傾向於通過擴展添加大部分功能。像這樣:通過擴展爲協議添加功能的原因是什麼,爲什麼不把它放在協議本身的定義中呢?
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)
}
}
}
}
擴展的背後是什麼?爲什麼不把它包含在最初的協議定義中呢?
以及爲什麼不延長的UIView編碼?我的意思是我們實際上最終擴展UIView的權利? – Honey
@Honey這是一個很好的問題,但這不是OP要求的。請不要改變主題。 – matt
我跟着我的問題可以發現[這裏](http://stackoverflow.com/questions/41706504/why-should-not-directly-extend-uiview-or-uiviewcontroller) – Honey