本文介绍了通过扩展将功能添加到协议的原因是什么,为什么不仅仅将其放在协议本身的定义中呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直想知道为什么当我看到协议示例时,人们倾向于通过扩展来添加大多数功能.像这样:
I've always wondered why when I see examples of protocols people tend to add most of the functions via an extension. Like this:
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)
}
}
}
}
扩展名的含义是什么?为什么不将其包括在初始协议定义中?
What's the point behind the extension? why not just include it in the initial protocol definition?
推荐答案
因为那是不合法的.协议可以包括功能声明,但不包括功能主体(实现).协议扩展即将包括默认实现.这就是协议扩展 的含义.
Because that's not legal. A protocol may include a function declaration but not the function body (the implementation). A protocol extension is about including a default implementation. That's what a protocol extension is.
这篇关于通过扩展将功能添加到协议的原因是什么,为什么不仅仅将其放在协议本身的定义中呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!