Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

Swift Protocol inheritance and protocol conformance issue

protocol BasePresenterProtocol : class {}
protocol DashboardPresenterProtocol : BasePresenterProtocol {}

final class DashboardPresenter {
    weak var view: DashboardPresenterProtocol?

    init() {
        self.view = DashboardViewController()
    }

    func test() {
        print("Hello")
    }
}

extension DashboardPresenter: DashboardViewProtocol { }

protocol BaseViewProtocol : class {
    weak var view: BasePresenterProtocol? { get set }
}

protocol DashboardViewProtocol : BaseViewProtocol {
}

class DashboardViewController {
}

extension DashboardViewController: DashboardPresenterProtocol { }

In the above code, I get an error at following line

extension DashboardPresenter: DashboardViewProtocol { }

that, DashboardPresenter doesn't confirm to protocol DashboardViewProtocol, but I have declared weak var view: DashboardPresenterProtocol? in DashboardPresenter . Although I have declared

Why am I getting this error ? Please let me know what I am doing wrong in this code.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot implement a read-write property requirement of type BasePresenterProtocol? with a property of type DashboardPresenterProtocol?.

Consider what would happen if this were possible, and you upcast an instance of DashboardPresenter to DashboardViewProtocol. You would be able to assign anything that conforms to BasePresenterProtocol to a property of type DashboardPresenterProtocol? – which would be illegal.

For this reason, a read-write property requirement has to be invariant (although it's worth noting that a readable-only property requirement should be able to be covariant – but this currently isn't supported).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...