我一直想知道为什么当我看到协议(protocol)示例时,人们倾向于通过扩展来添加大部分功能。像这样:
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)
}
}
}
}
扩展背后的意义是什么?为什么不将其包含在初始协议(protocol)定义中?
最佳答案
why not just include it in the initial protocol definition
因为那是不合法的。协议(protocol)可能包含函数声明,但不包含函数体(实现)。协议(protocol)扩展是关于包含默认实现。这就是协议(protocol)扩展。
关于ios - 通过扩展向协议(protocol)添加功能的原因是什么,为什么不把它放在协议(protocol)本身的定义中呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41646367/