Swift subprotocol with associated type

懵懂的女人 提交于 2019-12-11 04:38:56

问题


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
}

but this didn't work (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.

There are only two constraints:

  1. Sequence can't be a concrete type
  2. None of the methods on Index have a meaningful implementation

Notes:

  • 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.


回答1:


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

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


来源:https://stackoverflow.com/questions/48957492/swift-subprotocol-with-associated-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!