[英]associatedtype protocol conformance issues
I have 3 protocols to define a relationship where a Mediator
uses Host
to extract Client
我有 3 个协议来定义
Mediator
使用Host
提取Client
的关系
Host
Client
Mediator
My goal is to have Host
also act as a Mediator
.我的目标是让
Host
也充当Mediator
。 These are my class and protocol definitions:这些是我的 class 和协议定义:
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然后我扩展我的
MediatorProtocol
以添加一个实现
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现在,当我尝试使我的主机符合 MediatorProtocol 时,我收到一条错误消息
Type 'Host' does not conform to protocol MediatorProtocol
类型“主机”不符合协议 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.即使没有
where
规范,您也可以重写它。 Swift can infer associated types from function declaration (that's why it couldn't do so with your code). Swift 可以从 function 声明中推断出关联的类型(这就是为什么它不能用你的代码这样做)。
extension MediatorProtocol {
func getClientFrom(host: Host) -> Client? {
return Client()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.