微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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,但我已经声明了弱var视图:DashboardPresenterProtocol?在DashboardPresenter中.虽然我已经宣布了

为什么我收到此错误?请让我知道我在这代码中做错了什么.

解决方法

您无法实现BasePresenterProtocol类型的读写属性要求?具有DashboardPresenterProtocol类型的属性

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

出于这个原因,读写属性要求必须是不变的(尽管值得注意的是,只读的属性要求应该能够协变 – but this currently isn’t supported).

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐