我有一个基类实现了一个符合如下协议(protocol)的扩展:
protocol OptionsDelegate {
func handleSortAndFilter(opt: Options)
}
extension BaseViewController: OptionsDelegate {
func handleSortAndFilter(opt: Options) {
print("Base class implementation")
}
}
我有一个继承自 BaseViewController 的子类“InspirationsViewController”。我正在重写扩展中的协议(protocol)方法,如下所示:
extension InspirationsViewController {
override func handleSortAndFilter(opt: Options) {
print("Inside inspirations")
}
}
当我在子类扩展中重写“handleSortAndFilter”函数时出现错误:“Declerations in extensions cannot override yet”
但是当我实现 UITableView 数据源和委托(delegate)方法时,我没有看到类似的问题。
如何避免这个错误?
最佳答案
在 where 子句中使用协议(protocol)扩展。有用。 但我不建议您在代码库中包含此类内容。
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 - Swift 覆盖子类中的协议(protocol)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41344287/