【问题标题】:Swift override protocol methods in sub classesSwift 覆盖子类中的协议方法
【发布时间】:2017-05-11 16:31:12
【问题描述】:

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

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”函数时出现错误:“扩展中的Declarations cannot override yet”

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

如何避免这个错误?

【问题讨论】:

  • InspirationsViewController 不是子类,它是扩展。我认为你定义错了。应该是类InspirationsViewController: BaseViewController
  • @HossamGhareeb 他已经说过 InspirationsViewControllerBaseViewController 的子类,这是它的扩展。这个问题可能在 Swift 中没有实现,你应该从主类中重写,扩展是为了添加更多功能
  • 在扩展中我们不能覆盖超类的方法。
  • 请同时发布课程定义。添加class BaseViewController: UIViewController{}class InspirationsViewController: BaseViewController {} 的代码在这里编译得很好。
  • @shallowThought,你提到的类声明是正确的。

标签: ios swift overriding protocols ios-extensions


【解决方案1】:

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

【讨论】:

  • 非常感谢您的回答。您能否提供一些解释以了解实现?
  • 编译完美。但它从不调用“InsipartionsViewController”中实现的覆盖函数。
  • talk.objc.io/episodes/S01E29-protocols-class-hierarchies 快速查看有关协议和类层次结构的视频。
  • 嗯。我试过这个,但我无法调用协议方法。例如,让 x = InsipartionsViewController(); x.handleSortAndFilter(opt:...) 无法为我编译。
  • 啊。现在明白了,我得让 UIViewController 遵守协议。
【解决方案2】:

据我所知,您不能覆盖扩展中的方法。扩展只能执行以下操作: “Swift 中的扩展可以:

  • 添加计算实例属性和计算类型属性
  • 定义实例方法和类型方法
  • 提供新的初始化器
  • 定义下标
  • 定义和使用新的嵌套类型
  • 使现有类型符合协议”

摘自:Apple Inc. “Swift 编程语言 (Swift 3.0.1)。”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-26
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-21
    相关资源
    最近更新 更多