子类中的Swift覆盖协议方法

时间:2016-12-27 11:25:20

标签: ios swift override protocols ios-extensions

我的基类实现了符合协议的扩展,如下所示:

protocol OptionsDelegate {
    func handleSortAndFilter(opt: Options)
}

extension BaseViewController: OptionsDelegate {
    func handleSortAndFilter(opt: Options) {
        print("Base class implementation")
    }
}

我是一个子类" InspirationsViewController"继承自BaseViewController。我在扩展中覆盖了协议方法,如下所示:

extension InspirationsViewController {
    override func handleSortAndFilter(opt: Options) {
        print("Inside inspirations")
    }
}

当我覆盖" handleSortAndFilter"时,我收到错误子类扩展中的函数: "扩展中的疏散不能覆盖"

但是当我实现UITableView数据源和委托方法时,我没有看到类似的问题。

如何避免此错误?

2 个答案:

答案 0 :(得分:16)

使用where子句的协议扩展。它有效。

class BaseViewController: UIViewController {

}

extension OptionsDelegate where Self: BaseViewController {
  func handleSortAndFilter(opt: Options) {
    print("Base class implementation")
  }
}

extension BaseViewController: OptionsDelegate {

}

class InsipartionsViewController: BaseViewController {

}

extension OptionsDelegate where Self: InsipartionsViewController {
  func handleSortAndFilter(opt: Options) {
    print("Inspirations class implementation")
  }
}

答案 1 :(得分:3)

据我所知,你无法覆盖扩展中的方法。扩展程序只能执行以下操作: “Swift中的扩展可以:

  • 添加计算实例属性和计算类型属性
  • 定义实例方法和类型方法
  • 提供新的初始化程序
  • 定义下标
  • 定义并使用新的嵌套类型
  • 使现有类型符合协议“

摘自:Apple Inc.“The Swift Programming Language(Swift 3.0.1)。”

相关问题