Swift override protocol methods in sub classes

混江龙づ霸主 提交于 2019-12-12 07:47:09

问题


I've a base class that implements an extension that conforms to a protocol as below:

protocol OptionsDelegate {
    func handleSortAndFilter(opt: Options)
}

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

I've a subclass "InspirationsViewController" that inherits from BaseViewController. And I'm overriding protocol method in the extension as below:

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

I'm getting error when I override "handleSortAndFilter" function in subclass extension: "Declerations in extensions cannot override yet"

But I'm not seeing similar problem when I implemented UITableView datasource and delegate methods.

How to avoid this error?


回答1:


Use protocol extension with where clause. It works.

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



回答2:


As far as I know you can't override methods in extensions. Extensions can only do the following: “Extensions in Swift can:

  • Add computed instance properties and computed type properties
  • Define instance methods and type methods
  • Provide new initializers
  • Define subscripts
  • Define and use new nested types
  • Make an existing type conform to a protocol”

Excerpt From: Apple Inc. “The Swift Programming Language (Swift 3.0.1).”



来源:https://stackoverflow.com/questions/41344287/swift-override-protocol-methods-in-sub-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!