【问题标题】:Why associatedtype protocol fails to compile with error: does not conform to protocol为什么关联类型协议无法编译并出现错误:不符合协议
【发布时间】:2019-04-19 14:45:00
【问题描述】:

我尝试使用相关协议编译 Swift 文件,但编译失败并出现错误

import Foundation

protocol ViewProtocol {
}

protocol PresenterProtocol {
    associatedtype ViewType: ViewProtocol

    var view: ViewType {get}
}

protocol ExampleViewProtocol: ViewProtocol { 
}

class ExamplePresenter: PresenterProtocol {
    var view: ExampleViewProtocol

    init(view: ExampleViewProtocol) {
        self.view = view
    }
}

Xcode 10.2 和 XCode 10.1 出现错误:

类型“ExamplePresenter”不符合协议“PresenterProtocol”

我不明白为什么。应该怎么做才能编译?

【问题讨论】:

  • 参见Protocol doesn't conform to itself?ExampleViewProtocol ViewProtocol继承,但不符合它。
  • 当您有关联类型时,您的view 本身不能是协议。您需要使用具体类型。我的 Viper 结构也遇到了同样的问题。我不想使用具体类型,但我希望公共代码驻留在基类中。如果我找到解决方案,我会通知您。
  • 这看起来也像是对协议的滥用。您可能意味着 Presenter 是通用的,而不是协议。什么通用算法会使用 PresenterProtocol(请记住,您不能将这些演示者放在变量或数组中,因为这是 PAT)?协议不是抽象基类(看起来你也可以像这里一样对待它们)。

标签: swift


【解决方案1】:

问题是ExampleViewProtocol 继承自ViewProtocol 而不是遵循它。要使您的代码编译,您可以尝试调整ExampleViewProtocol 使其成为一个类。这将使ExampleViewProtocol 成为一个具体类型,使其符合ViewProtocol

【讨论】:

【解决方案2】:

您可以向 ExamplePresenter 添加泛型类型约束

class ExamplePresenter<T: ExampleViewProtocol>: PresenterProtocol {
    typealias ViewType = T

    var view: T

    init(view: T) {
        self.view = view
    }
}

【讨论】:

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