子类中的Swift覆盖协议方法 [英] Swift override protocol methods in sub classes
问题描述
我有一个基类,它实现了一个符合协议的扩展,如下所示:
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")
}
}
我有一个继承的子类InspirationsViewController来自BaseViewController。我在扩展中重写协议方法如下:
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")
}
}
当我在子类扩展中覆盖handleSortAndFilter函数时出现错误: 扩展中的疏忽无法覆盖
I'm getting error when I override "handleSortAndFilter" function in subclass extension: "Declerations in extensions cannot override yet"
但是当我实现UITableView数据源和委托方法时,我没有看到类似的问题。
But I'm not seeing similar problem when I implemented UITableView datasource and delegate methods.
如何避免这个错误?
推荐答案
将协议扩展名与where子句一起使用。它有效。
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")
}
}
这篇关于子类中的Swift覆盖协议方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!