Search code examples
iosswiftviper-architectureprotocol-oriented

Protocol Oriented Programming in swift iOS


Here is the 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 will have all the routing functions. HomeWireFrameProtocol will extend and have some home relating routing only. The test class inherits from HomeInteractorProtocol, which has a var wireFrame: HomeWireFrameProtocol, again HomeWireFrameProtocol is extending WireFrameProtocol.

Is var wireFrame: HomeWireFrameProtocol also represent var wireFrame: WireFrameProtocol?


Solution

  • Ok I realise it now, and fixed my own problem. What I did was

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

    The variable wireFrame: WireFrameProtocol can also hold the reference of HomeWireFrameProtocol.

    so in Test class I updated:

    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{
        
    }