具有关联类型的Swift子协议

编程入门 行业动态 更新时间:2024-10-24 08:29:10
本文介绍了具有关联类型的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.

只有两个约束:

  • 序列不能是具体类型
  • 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子协议

    本文发布于:2023-10-28 08:32:18,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1536105.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:协议   类型   Swift

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!