我有 3 个协议来定义关系,其中 Mediator
使用 Host
提取 Client
Host
Client
Mediator
我的目标是让 Host
也充当 Mediator
。这些是我的类和协议定义:
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?
}
然后我扩展我的 MediatorProtocol
以添加一个实现
extension MediatorProtocol where H == Host, C == Client {
func getClientFrom(host: H) -> C? {
return Client()
}
}
现在,当我尝试使我的主机符合 MediatorProtocol 时,我收到一条错误消息
<块引用>Type 'Host' 不符合协议 MediatorProtocol
extension Host: MediatorProtocol {}
有什么想法吗?
答案 0 :(得分:1)
只需更改此协议规范
extension MediatorProtocol where H == Host, C == Client {
func getClientFrom(host: Host) -> Client? {
return Client()
}
}
即使没有 where
规范,您也可以重写它。 Swift 可以从函数声明中推断出关联类型(这就是为什么它不能对您的代码这样做)。
extension MediatorProtocol {
func getClientFrom(host: Host) -> Client? {
return Client()
}
}