【发布时间】:2018-02-23 23:08:08
【问题描述】:
我想知道这种类型的关系(在 kotlin 中的例子)在 Swift 中是如何表达的
interface Index<K, V> {
fun getAll(key: K): Sequence<V>
}
我尝试使用具有关联类型的协议,如下所示:
protocol Index {
associatedtype Key
associatedtype Value
associatedtype Result: Sequence where Sequence.Element == Value
func getAll(key: Key) -> Result
}
但这不起作用 (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
}
但这似乎并不是正确/惯用的方法。
只有两个约束:
- 序列不能是具体类型
- Index 上的所有方法都没有有意义的实现
注意事项:
- 会有一个实现
Sequence的类/类型特定于Index的每个实现
我对任何其他结构性变化持开放态度! 提前致谢。
【问题讨论】:
标签: swift generics swift-protocols associated-types