【问题标题】:Swift Protocol inheritance and protocol conformance issueSwift 协议继承和协议一致性问题
【发布时间】:2016-11-03 20:43:07
【问题描述】:
protocol BasePresenterProtocol : class {}
protocol DashboardPresenterProtocol : BasePresenterProtocol {}

final class DashboardPresenter {
    weak var view: DashboardPresenterProtocol?

    init() {
        self.view = DashboardViewController()
    }

    func test() {
        print("Hello")
    }
}

extension DashboardPresenter: DashboardViewProtocol { }

protocol BaseViewProtocol : class {
    weak var view: BasePresenterProtocol? { get set }
}

protocol DashboardViewProtocol : BaseViewProtocol {
}

class DashboardViewController {
}

extension DashboardViewController: DashboardPresenterProtocol { }

在上面的代码中,我在下一行得到一个错误

extension DashboardPresenter: DashboardViewProtocol { }

那个,DashboardPresenter 没有确认协议DashboardViewProtocol,但我已经在DashboardPresenter 中声明了weak var view: DashboardPresenterProtocol?。虽然我已经声明了

为什么会出现这个错误?请让我知道我在这段代码中做错了什么。

【问题讨论】:

    标签: swift swift-protocols


    【解决方案1】:

    您不能使用DashboardPresenterProtocol? 类型的属性来实现BasePresenterProtocol? 类型的读写属性要求。

    考虑如果这可能会发生什么,并且您将DashboardPresenter 的实例向上转换为DashboardViewProtocol。您可以将符合 BasePresenterProtocol 的任何内容分配给 DashboardPresenterProtocol? 类型的属性——这是非法的。

    因此,读写属性要求必须是不变的(尽管值得注意的是,只读属性要求应该能够是协变的——but this currently isn't supported)。 p>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多