[英]How to implement specific type of protocol in a protocol
I have a protocol named ViperPresenterProtocol that contains a property protocol named ViperInteractorProtocol.我有一个名为 ViperPresenterProtocol 的协议,其中包含一个名为 ViperInteractorProtocol 的属性协议。
Now, I want to have another protocol that extends ViperPresenterProtocol and returns a different type.现在,我想要另一个扩展 ViperPresenterProtocol 并返回不同类型的协议。 But, when a class confirm to the TestPresenterProtocol, I want to implement only the TestInteractorProtocol.
但是,当 class 向 TestPresenterProtocol 确认时,我只想实现 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.使子协议
TestPresenterProtocol
扩展它的定义并符合父协议要求将允许您创建符合子协议的 class 以仅具有对子协议的要求而不是父协议的要求。 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.在这种情况下,具有相同名称的
interactor
器会使编译器感到困惑。 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?
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.