Swift 协议(protocol)继承和协议(protocol)一致性问题
<p><pre><code>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 { }
</code></pre>
<p>在上面的代码中,我在下一行得到一个错误</p>
<pre><code>extension DashboardPresenter: DashboardViewProtocol { }
</code></pre>
<p>那个,<code>DashboardPresenter</code> 没有确认协议(protocol) <code>DashboardViewProtocol</code>,但是我在 <code>DashboardPresenter 中声明了 <code>weak var view: DashboardPresenterProtocol?</code> </code> 。虽然我已经声明了</p>
<p>为什么会出现这个错误?请让我知道我在这段代码中做错了什么。</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>您不能使用 <code>DashboardPresenterProtocol?</code> 类型的属性来实现 <code>BasePresenterProtocol?</code> 类型的读写属性要求。</p>
<p>考虑一下如果这<em>是</em>可能会发生什么,并且您将 <code>DashboardPresenter</code> 的实例向上转换为 <code>DashboardViewProtocol</code>。您可以将符合 <code>BasePresenterProtocol</code> 的任何内容分配给 <code>DashboardPresenterProtocol?</code> 类型的属性——这是非法的。</p>
<p>因此,读写属性要求<em>必须</em>是不变的(尽管值得注意的是,只读属性要求应该能够是协变的——<a href="https://stackoverflow.com/q/42561685/2976878" rel="noreferrer noopener nofollow">but this currently isn't supported</a>)。</em> p></p>
<p style="font-size: 20px;">关于Swift 协议(protocol)继承和协议(protocol)一致性问题,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/43254573/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/43254573/
</a>
</p>
页:
[1]