快速iOS中的面向协议编程



这是Protocols

protocol WireFrameProtocol{
// router for all normal cases
// like showing login page

}
protocol InteractorProtocol{
var wireFrame: WireFrameProtocol? { get set }
}
protocol HomeWireFrameProtocol: WireFrameProtocol{
// home specific routers
}
protocol HomeInteractorProtocol: InteractorProtocol{
var wireFrame: HomeWireFrameProtocol? { get set }
}
class Test: HomeInteractorProtocol{
var wireFrame: HomeWireFrameProtocol?
}
extension Test: InteractorProtocol{

}

WireFrameProtocol将具有所有路由功能。HomeWireFrameProtocol将扩展并仅具有一些与家庭相关的路由。测试类继承自HomeInteractorProtocol,它有一个 var wireFrame:HomeWireFrameProtocol,同样HomeWireFrameProtocol扩展WireFrameProtocol

var wireFrame: HomeWireFrameProtocol也代表var wireFrame: WireFrameProtocol吗?

好的,我现在意识到了,并解决了我自己的问题。我所做的是

protocol HomeInteractorProtocol: InteractorProtocol{
// do not create another variable to store HomeWireFrame
// var wireFrame: HomeWireFrameProtocol? { get set }
}

变量wireFrame: WireFrameProtocol也可以保存HomeWireFrameProtocol的引用。

所以在测试类中我更新了:

class Test: HomeInteractorProtocol{
// can use all features from the WireFrameProtocol
var wireFrame: WireFrameProtocol?
// also can use all the feature from HomeWireFrame
// this is kind of what I want to achieve without creating two different variables in the protocols
var homeWireFrame: HomeWireFrameProtocol? {
return wireFrame as? HomeWireFrameProtocol
}
}
extension Test: InteractorProtocol{

}

如果我正确理解了您的问题,那么您刚刚遇到了一个传统的Dimond Problem,其中特定功能继承自哪个父类是模棱两可的。

您的viewwireFrameHomeViewPresenterProtocolHomeViewInteractorOutputProtocol中声明的变量。因此,当您确认这两个协议时HomeViewPresenter就会出现戴蒙德问题。编译器让这个模棱两可的父级感到困惑。

最简单的解决方案是更改变量名称,因为不能具有相同的变量或函数签名。

最新更新