Mor*_*ger 1 generics associated-types swift swift-protocols
我想知道如何在Swift中表达这种类型的关系(例如kotlin中的示例)
interface Index<K, V> {
fun getAll(key: K): Sequence<V>
}
Run Code Online (Sandbox Code Playgroud)
我试图使用具有关联类型的协议,如下所示:
protocol Index {
associatedtype Key
associatedtype Value
associatedtype Result: Sequence where Sequence.Element == Value
func getAll(key: Key) -> Result
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用(Associated type 'Element' can only be used with a concrete type or generic parameter base)
然后,作为一种解决方法,我尝试了此操作:
protocol Index {
associatedtype Key
associatedtype Value
func get<T: Sequence>(key: Key) -> T where T.Element == Value
}
Run Code Online (Sandbox Code Playgroud)
但这似乎并不是正确/惯用的方法。
只有两个约束:
笔记:
Sequence特定于每个实现的类/类型Index我愿意接受任何其他结构性改变!提前致谢。
您需要使用关联的类型名称,而不是继承的协议名称:
associatedtype Result: Sequence where Result.Element == Value
// ^^^^^^
Run Code Online (Sandbox Code Playgroud)