ios – 子类中的Swift覆盖协议方法

我有一个基类,它实现了一个符合协议的扩展,如下所示:
protocol OptionsDelegate {
    func handleSortAndFilter(opt: Options)
}

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

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

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

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

但是当我实现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")
  }
}

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...