Swift 具有关联类型的子协议
Swift subprotocol with associated type
我想知道这种类型的关系(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
}
但这似乎并不是正确/惯用的方法。
只有两个约束:
- 序列不能是具体类型
- None 的 Index 方法具有有意义的实现
备注:
- 将有一个 class / 实现
Sequence
的类型,它特定于 Index
的每个实现
我愿意接受任何其他结构性变化!
提前致谢。
您需要使用关联类型的名称,而不是继承协议的名称:
associatedtype Result: Sequence where Result.Element == Value
// ^^^^^^
请注意,Swift 的标准库现在包含一个名为 Result
的类型,因此您可能希望为 associatedtype
使用不同的名称。我在自己的代码中使用 Answer
:
associatedtype Answer: Sequence where Answer.Element == Value
(在 Smalltalk 中,return 值称为“答案”。)
我想知道这种类型的关系(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
}
但这似乎并不是正确/惯用的方法。
只有两个约束:
- 序列不能是具体类型
- None 的 Index 方法具有有意义的实现
备注:
- 将有一个 class / 实现
Sequence
的类型,它特定于Index
的每个实现
我愿意接受任何其他结构性变化! 提前致谢。
您需要使用关联类型的名称,而不是继承协议的名称:
associatedtype Result: Sequence where Result.Element == Value
// ^^^^^^
请注意,Swift 的标准库现在包含一个名为 Result
的类型,因此您可能希望为 associatedtype
使用不同的名称。我在自己的代码中使用 Answer
:
associatedtype Answer: Sequence where Answer.Element == Value
(在 Smalltalk 中,return 值称为“答案”。)