swift - 使用从另一个协议继承的协议作为关联类型
问题描述
我正在尝试制作一个具有两种关联类型的协议。这些关联类型之一用于委托。当我尝试使用另一个协议作为关联类型时,我收到错误“类型‘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”(又名“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>()
推荐阅读
- angular - 如何根据id取json键值
- r - 如何保存/加载通过 R 中的 h2o4gpu 库创建的随机森林模型?
- android - 如何在 Android 8.1 上访问 DCIM 文件夹
- go - 寻找一种在 golang mysql 中查看插值查询的方法
- flutter - 如何使用可滚动小部件绘制一个带有复杂标题的 UI?
- php - 表单数据的恢复
- kubernetes - 如何将 gitlab ci/cd 变量传递给 kubernetes(AKS) deployment.yaml
- c#-4.0 - 我想在 C# 中显示按列名“RefPI”分组的数据。我有一个数据表,怎么做
- sql-server - 带有子查询的用户定义函数
- flutter - 使用flutter和webview登录joomla网站