[英]Use protocol that inherits from another protocol as an associated type
I am trying to make a protocol that has has two associated types. 我正在尝试制作一个具有两个关联类型的协议。 One of these associated types is for a delegate.
这些关联类型之一是用于委托的。 When I try to use another protocol as the associated type, I get the error "Type 'HostConnectionService' does not conform to protocol 'ConnectionService'".
当我尝试使用另一个协议作为关联类型时,出现错误“类型'HostConnectionService'不符合协议'ConnectionService'”。 The code I have is written below:
我的代码如下:
protocol ConnectionService: class {
associatedtype Peer: Sharelist.Peer
associatedtype Delegate: ConnectionServiceDelegate
var connectedPeers: [Peer] { get }
var delegate: Delegate? { get }
}
protocol ConnectionServiceDelegate { }
// Error
class HostConnectionService: NSObject, ConnectionService {
typealias Peer = GuestPeer
typealias Delegate = HostConnectionServiceDelegate
var delegate: HostConnectionServiceDelegate?
var connectedPeers: [GuestPeer] = []
}
protocol HostConnectionServiceDelegate: ConnectionServiceDelegate { }
When I change the line 当我换线时
typealias Delegate = HostConnectionServiceDelegate
to be of a non-protocol type, I no longer get an error: 成为非协议类型,我不再收到错误:
struct NonProtocolConnectionServiceDelegate: ConnectionServiceDelegate { }
// No Error
class HostConnectionSertice: NSObject, ConnectionService {
...
typealias Delegate = NonProtocolConnectionServiceDelegate
...
}
Is this a fundamental Swift limitation, or am I doing something wrong? 这是Swift的基本限制,还是我做错了什么?
Your example is too complicated to understand. 您的示例太复杂,难以理解。 I tried to simplify it.
我试图简化它。
It compiles without errors: 它编译没有错误:
protocol ProtocolA {}
protocol ProtocolB {
associatedtype SomeType
}
class SomeClass: ProtocolB {
typealias SomeType = ProtocolA
}
let object = SomeClass()
But the following example is no longer compiled: 但是下面的示例不再编译:
protocol ProtocolA {}
protocol ProtocolB {
associatedtype SomeType: ProtocolA
}
class SomeClass: ProtocolB {
typealias SomeType = ProtocolA
}
The error is as follows: 错误如下:
error: type 'SomeClass' does not conform to protocol 'ProtocolB'
错误:类型“ SomeClass”不符合协议“ ProtocolB”
note: possibly intended match 'SomeType' (aka 'ProtocolA') does not conform to 'ProtocolA'
注意:可能的预期匹配项'SomeType'(aka'ProtocolA')不符合'ProtocolA'
This is because protocols don't conform to themselves 这是因为协议不符合自己
Most likely in your case it is necessary to make the class template: 在您的情况下,最有可能需要制作类模板:
protocol ProtocolA {}
protocol ProtocolB {
associatedtype SomeType: ProtocolA
}
class SomeClass<T: ProtocolA>: ProtocolB {
typealias SomeType = T
}
extension Int: ProtocolA {}
extension Double: ProtocolA {}
let object1 = SomeClass<Int>()
let object2 = SomeClass<Double>()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.