I have 3 protocols to define a relationship where a Mediator
uses Host
to extract Client
Host
Client
Mediator
My goal is to have Host
also act as a Mediator
. These are my class and protocol definitions:
class Host {}
class Client {}
protocol HostProtocol {}
protocol ClientProtocol {}
extension Host: HostProtocol {}
extension Client: ClientProtocol {}
protocol MediatorProtocol {
associatedtype H = HostProtocol
associatedtype C = ClientProtocol
func getClientFrom(host: H) -> C?
}
I then extend my MediatorProtocol
to add an implementation
extension MediatorProtocol where H == Host, C == Client {
func getClientFrom(host: H) -> C? {
return Client()
}
}
Now when I try to make my Host conform to MediatorProtocol, I get an error saying
Type 'Host' does not conform to protocol MediatorProtocol
extension Host: MediatorProtocol {}
Any ideas?
Just change protocol specification on this
extension MediatorProtocol where H == Host, C == Client {
func getClientFrom(host: Host) -> Client? {
return Client()
}
}
You can rewrite it even without where
spec. Swift can infer associated types from function declaration (that's why it couldn't do so with your code).
extension MediatorProtocol {
func getClientFrom(host: Host) -> Client? {
return Client()
}
}
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.