问题描述
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 { }
在上面的代码中,我在下面一行出现错误
In the above code, I get an error at following line
extension DashboardPresenter: DashboardViewProtocol { }
那个,DashboardPresenter
不确认协议 DashboardViewProtocol
,但我在 DashboardPresenter 中声明了
weak var view: DashboardPresenterProtocol?
代码> .虽然我已经声明
that, DashboardPresenter
doesn't confirm to protocol DashboardViewProtocol
, but I have declared weak var view: DashboardPresenterProtocol?
in DashboardPresenter
. Although I have declared
为什么我会收到这个错误?请让我知道我在这段代码中做错了什么.
Why am I getting this error ? Please let me know what I am doing wrong in this code.
推荐答案
您不能使用 DashboardPresenterProtocol 类型的属性实现
BasePresenterProtocol?
类型的读写属性要求?>.
You cannot implement a read-write property requirement of type BasePresenterProtocol?
with a property of type DashboardPresenterProtocol?
.
考虑一下如果这可能会发生什么,并且您将 DashboardPresenter
的实例向上转换为 DashboardViewProtocol
.您可以将任何符合 BasePresenterProtocol
的内容分配给 DashboardPresenterProtocol?
类型的属性——这将是非法的.
Consider what would happen if this were possible, and you upcast an instance of DashboardPresenter
to DashboardViewProtocol
. You would be able to assign anything that conforms to BasePresenterProtocol
to a property of type DashboardPresenterProtocol?
– which would be illegal.
出于这个原因,读写属性要求必须保持不变(尽管值得注意的是,只读属性要求应该能够协变——但目前不支持).
For this reason, a read-write property requirement has to be invariant (although it's worth noting that a readable-only property requirement should be able to be covariant – but this currently isn't supported).
这篇关于Swift 协议继承和协议一致性问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!