简体   繁体   中英

How to implement specific type of protocol in a protocol

I have a protocol named ViperPresenterProtocol that contains a property protocol named ViperInteractorProtocol.

Now, I want to have another protocol that extends ViperPresenterProtocol and returns a different type. But, when a class confirm to the TestPresenterProtocol, I want to implement only the TestInteractorProtocol.

protocol ViperInteractorProtocol {}
protocol TestInteractorProtocol: ViperInteractorProtocol {}

protocol ViperPresenterProtocol {
    var interactor: ViperInteractorProtocol? { get set }
}

protocol TestPresenterProtocol2: ViperPresenterProtocol {
    var interactor: TestInteractorProtocol? { get set }
}

class TestPresenter: TestPresenterProtocol {
    var interactor: TestInteractorProtocol?  //  Compile error
    var interactor: ViperInteractorProtocol?  //
}

Making the child-protocol TestPresenterProtocol extend it's definition and conform to the parent-protocol requirement would allow you to create class that conforms to the child-protocol to only have the requirements for child-protocol and not the parent-protocol. The only requirement that's needed for that is the compiler must be able to distinguish between the properties. With the same name in this case interactor confuses the compiler. Hope this will help you in some way.

protocol ViperInteractorProtocol { }
protocol TestInteractorProtocol: ViperInteractorProtocol { }

protocol ViperPresenterProtocol {
    var interactor: ViperInteractorProtocol? { get set }
}

protocol TestPresenterProtocol: ViperPresenterProtocol {
    var testInteractor: TestInteractorProtocol? { get set }
}

extension TestPresenterProtocol {
    var interactor: ViperInteractorProtocol? {
        set { interactor = newValue }
        get { testInteractor }
    }
}

class TestPresenter: TestPresenterProtocol {
    var testInteractor: TestInteractorProtocol?
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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