I try to compile Swift file with associated protocol and it fails to compile with error
import Foundation
protocol ViewProtocol {
}
protocol PresenterProtocol {
associatedtype ViewType: ViewProtocol
var view: ViewType {get}
}
protocol ExampleViewProtocol: ViewProtocol {
}
class ExamplePresenter: PresenterProtocol {
var view: ExampleViewProtocol
init(view: ExampleViewProtocol) {
self.view = view
}
}
Error appears in Xcode 10.2 and XCode 10.1:
Type 'ExamplePresenter' does not conform to protocol 'PresenterProtocol'
I don't understand why. What should be done to make it compile?
The problem is that the ExampleViewProtocol
inherits from ViewProtocol
instead of conforming to it. To make your code compile, you could try adapting ExampleViewProtocol
to make it a class. This would make ExampleViewProtocol
a concrete type which will allow it to conform to ViewProtocol
.
you can add generic type constraints to ExamplePresenter
class ExamplePresenter<T: ExampleViewProtocol>: PresenterProtocol {
typealias ViewType = T
var view: T
init(view: T) {
self.view = view
}
}
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.