子类中的Swift覆盖协议方法

我有一个基类,它实现了一个符合如下协议的扩展:

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

我有一个inheritance自BaseViewController的子类“InspirationsViewController”。 而我在覆盖扩展协议方法如下:

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

当我在子类扩展中覆盖“handleSortAndFilter”函数时出现错误: “扩展中的Declerations无法覆盖”

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

如何避免这个错误?

在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") } } 

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

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

摘录自:苹果公司“Swift编程语言(Swift 3.0.1)”。