本文介绍了具有关联类型的Swift子协议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在Swift中表达这种类型的关系(例如kotlin中的例子)

I'd like to know how this type of relation (example in kotlin) would be expressed in Swift

interface Index<K, V> {
  fun getAll(key: K): Sequence<V>
}

我试图使用具有关联类型的协议,例如:

I tried to use protocols with associated types, like this:

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)

然后,作为一种解决方法,我尝试了此操作:

Then, as a workaround, i tried this:

protocol Index {
    associatedtype Key
    associatedtype Value

    func get<T: Sequence>(key: Key) -> T where T.Element == Value
}

但是,这似乎并不是正确/惯用的方式.

But this doesn't really seem like the right / idiomatic way to do it.

只有两个约束:

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

注意:

  • 将存在一个实现Sequence的类/类型,该类/类型特定于Index的每种实现
  • There will be a class / type that implements Sequence that is specific to each implementation of Index

我愿意接受任何其他结构性改变!预先感谢.

I'm open to any other structural change!Thanks in advance.

推荐答案

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

You need to use the associated type's name, not the inherited protocol's name:

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

这篇关于具有关联类型的Swift子协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 03:58