【发布时间】: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