我一直想知道为什么当我看到协议示例时,人们倾向于通过扩展添加大部分功能。像这样:
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)
}
}
}
}
扩展背后的意义是什么?为什么不将它包含在初始协议定义中?