在子类中重写Swift协议方法

19

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

protocol OptionsDelegate {
    func handleSortAndFilter(opt: Options)
}

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

我有一个子类"InspirationsViewController",它继承自"BaseViewController"。我正在通过扩展来重写协议方法,如下所示:

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

在子类扩展中覆盖“handleSortAndFilter”函数时出现错误:"Declerations in extensions cannot override yet"

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

如何避免此错误?


InspirationsViewController is not a subclass, its an extension. I think you defined it wrong. It should be a class InspirationsViewController: BaseViewController - Hossam Ghareeb
2
@HossamGhareeb 他已经说过 InspirationsViewControllerBaseViewController 的子类,这是对它的扩展。这个问题可能还没有在 Swift 中实现,你应该从主类中进行重写,扩展是用于添加更多功能的。 - Tj3n
在扩展中,我们无法覆盖超类的方法。 - Aman Gupta
请附上类定义。将以下代码添加到此处后,代码可以正常编译: class BaseViewController: UIViewController{}class InspirationsViewController: BaseViewController {} - shallowThought
@shallowThought,你提到的类声明是正确的。 - Satyam
2个回答

27

使用带有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")
  }
}

非常感谢您的回答。您能否提供一些解释以便理解实现过程? - Satyam
1
它编译得很完美。但它从未调用在“InspirationsViewController”实现的覆盖函数。 - Satyam
看看这个关于Swift中协议和类层次结构的视频。 - Igor Bidiniuc
嗯,我尝试了这个,但是我无法调用协议方法。例如,让x = InsipartionsViewController(); x.handleSortAndFilter(opt:...) 对我来说无法编译。 - Chris Prince
啊,我明白了,我必须让UIViewController遵守该协议。 - Chris Prince
这太棒了!不幸的是,方法无法访问类的内部属性(私有)。例如:它无法访问InspirationsViewController中的私有变量。 - TheJeff

5
据我所知,您不能在扩展中覆盖方法。扩展只能执行以下操作: “Swift 中的扩展可以:”
  • 添加计算实例属性和计算类型属性
  • 定义实例方法和类型方法
  • 提供新的初始化程序
  • 定义下标
  • 定义和使用新的嵌套类型
  • 使现有类型符合协议”

摘自:苹果公司。“The Swift Programming Language (Swift 3.0.1).”


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接