具有相关类型的Swift子协议

时间:2018-02-23 23:08:08

标签: swift generics swift-protocols associated-types

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

user,time_from,time_to
user1,19:10,19:20
user2,10:00,22:00
user3,18:00,18:59

我尝试使用具有相关类型的协议,如下所示:

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

但这似乎不是正确/惯用的方式。

只有两个限制因素:

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

    • 将会有一个实现protocol Index { associatedtype Key associatedtype Value func get<T: Sequence>(key: Key) -> T where T.Element == Value } 的类/类型,该类/类型特定于Sequence的每个实现

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

1 个答案:

答案 0 :(得分:4)

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

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

如果您想知道为什么需要这样做,请考虑一下:

class Either<A, B> { }

protocol Index {
    associatedtype Key
    associatedtype Value
    associatedtype Result: Either<Sequence, Sequence> where Sequence.Element == Value
    // error: associated type 'Element' can only be used with a concrete type or generic parameter base

    func getAll(key: Key) -> Result
}

此处,Result类型是由Sequence的两个实例构建的。您是否尝试指定A元素类型或B元素类型?它可以是,或两者兼而有之。你必须具体:

associatedtype Result: Either<Sequence, Sequence> where Result.A.Element == Value