具有关联类型的 Swift 子协议

2024-04-23

我想知道这种类型的关系(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
}

但这似乎并不是正确/惯用的做法。

只有两个限制:

  1. 序列不能是具体类型
  2. Index 上的方法都没有有意义的实现

Notes:

  • 将会有一个类/类型实现Sequence这是特定于每个实现的Index

我对任何其他结构性变化持开放态度! 提前致谢。


您需要使用关联类型的名称,而不是继承协议的名称:

associatedtype Result: Sequence where Result.Element == Value
//                                    ^^^^^^

请注意,Swift 的标准库现在包含一个名为Result,所以您可能想为您的名称使用不同的名称associatedtype. I use Answer在我自己的代码中:

associatedtype Answer: Sequence where Answer.Element == Value

(在 Smalltalk 中,返回值称为“答案”。)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

具有关联类型的 Swift 子协议 的相关文章

随机推荐