子类中的Swift覆盖协议方法

Sat*_*yam 11 overriding protocols ios swift ios-extensions

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

protocol OptionsDelegate {
    func handleSortAndFilter(opt: Options)
}

extension BaseViewController: OptionsDelegate {
    func handleSortAndFilter(opt: Options) {
        print("Base class implementation")
    }
}
Run Code Online (Sandbox Code Playgroud)

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

extension InspirationsViewController {
    override func handleSortAndFilter(opt: Options) {
        print("Inside inspirations")
    }
}
Run Code Online (Sandbox Code Playgroud)

当我在子类扩展中覆盖"handleSortAndFilter"函数时,我收到错误:"扩展中的延迟无法覆盖"

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

如何避免这个错误?

Igo*_*iuc 18

使用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")
  }
}
Run Code Online (Sandbox Code Playgroud)


Hos*_*eeb 5

据我所知,您无法覆盖扩展中的方法。扩展只能执行以下操作:\n\xe2\x80\x9cSwift 中的扩展可以:

\n\n
    \n
  • 添加计算实例属性和计算类型属性
  • \n
  • 定义实例方法和类型方法
  • \n
  • 提供新的初始化器
  • \n
  • 定义下标
  • \n
  • 定义和使用新的嵌套类型
  • \n
  • 使现有类型符合协议\xe2\x80\x9d
  • \n
\n\n

摘自:Apple Inc. \xe2\x80\x9cThe Swift 编程语言 (Swift 3.0.1).\xe2\x80\x9d

\n