Swift 协议(protocol)继承和协议(protocol)一致性问题

标签 swift swift-protocols

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? 。虽然我已经声明

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

最佳答案

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

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

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

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

相关文章:

ios - 如何在 Swift 中从自定义文本生成 UIImage

swift - 替换时出现字符串错误

ios - 有没有办法在 SwiftUI 中仅针对某些 View 强制使用横向模式?

swift - 纹理 Swift SKPhysicsbody 的碰撞问题

swift - 从 firebase swift 读取数据

ios - UIViewController 的默认自定义过渡

ios - 具有内部函数和属性的 Swift 公共(public)协议(protocol)

swift - 继承通用协议(protocol)

ios - UIView 中的协议(protocol)无法更改 viewController 中的对象?

ios - 如何将 Decodable.Protocol 对象保存到变量?