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