![](/img/trans.png)
[英]Setting protocol which inherits from another protocol as associated type produces error
[英]Use protocol that inherits from another protocol as an associated type
我正在尝试制作一个具有两个关联类型的协议。 这些关联类型之一是用于委托的。 当我尝试使用另一个协议作为关联类型时,出现错误“类型'HostConnectionService'不符合协议'ConnectionService'”。 我的代码如下:
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 { }
当我换线时
typealias Delegate = HostConnectionServiceDelegate
成为非协议类型,我不再收到错误:
struct NonProtocolConnectionServiceDelegate: ConnectionServiceDelegate { }
// No Error
class HostConnectionSertice: NSObject, ConnectionService {
...
typealias Delegate = NonProtocolConnectionServiceDelegate
...
}
这是Swift的基本限制,还是我做错了什么?
您的示例太复杂,难以理解。 我试图简化它。
它编译没有错误:
protocol ProtocolA {}
protocol ProtocolB {
associatedtype SomeType
}
class SomeClass: ProtocolB {
typealias SomeType = ProtocolA
}
let object = SomeClass()
但是下面的示例不再编译:
protocol ProtocolA {}
protocol ProtocolB {
associatedtype SomeType: ProtocolA
}
class SomeClass: ProtocolB {
typealias SomeType = ProtocolA
}
错误如下:
错误:类型“ SomeClass”不符合协议“ ProtocolB”
注意:可能的预期匹配项'SomeType'(aka'ProtocolA')不符合'ProtocolA'
这是因为协议不符合自己
在您的情况下,最有可能需要制作类模板:
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.