OGeek|极客世界-中国程序员成长平台

标题: Swift 协议(protocol)继承和协议(protocol)一致性问题 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:26
标题: Swift 协议(protocol)继承和协议(protocol)一致性问题

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 没有确认协议(protocol) DashboardViewProtocol,但是我在 DashboardPresenter 中声明了 weak var view: DashboardPresenterProtocol? 。虽然我已经声明了

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



Best Answer-推荐答案


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

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

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

关于Swift 协议(protocol)继承和协议(protocol)一致性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43254573/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4