簡體   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