ios - 通过扩展向协议(protocol)添加功能的原因是什么,为什么不把它放在协议(protocol)本身的定义中呢?

标签 ios swift protocols protocol-oriented

我一直想知道为什么当我看到协议(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/

相关文章:

swift - insertRowsAtIndexPaths 跳转自定义单元格 UITableView 和 UITableViewAutomaticDimension

ios - UI线程中长时间运行的任务

networking - 是否有任何协议(protocol)规范允许使用 TCP 或 UDP?

iOS - 自己的 VoIP Asterisk 客户端应用程序

ios - 关闭 viewController 总是触发 viewDidLoad 并且从不触发 viewWillAppear

ios - 属性是否需要强关键字?

database - 遵守数据模型协议(protocol)的优势

使用 CollectionType 的 Swift 协议(protocol)和协议(protocol)扩展

ios - Swift SearchBar 如何在以编程方式更改后获取原始搜索图标

ios - 如何将搜索栏添加到 Collection View Controller ?