小编典典

Swift协议继承和协议一致性问题

swift

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,但我已weak var view: DashboardPresenterProtocol?在中声明DashboardPresenter。虽然我已经宣布

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


阅读 506

收藏
2020-07-07

共1个答案

小编典典

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

考虑这是否会发生什么
可能的,你上溯造型的一个实例,并DashboardPresenterDashboardViewProtocol。您将能够分配符合BasePresenterProtocol类型属性的任何内容,DashboardPresenterProtocol?这将是非法的。

因此,读写属性要求 _必须_是不变的(尽管值得注意的是,只读属性要求应该可以是协变的,但是当前不支持。

2020-07-07