繁体   English   中英

swift iOS 中的面向协议编程

[英]Protocol Oriented Programming in swift iOS

这是协议:

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 将扩展并仅具有一些与家庭相关的路由。 测试 class 继承自 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 我更新了:

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 ,在该问题中,特定功能是从哪个父 class 继承的不明确。

您的viewwireFrame都是在HomeViewPresenterProtocolHomeViewInteractorOutputProtocol中声明的变量。 因此,当您在HomeViewPresenter中确认这两个协议时,就会出现 Dimond 问题。 编译器对这个模棱两可的父母感到困惑。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM