【问题标题】:Swift subprotocol with associated type具有关联类型的 Swift 子协议
【发布时间】:2018-02-23 23:08:08
【问题描述】:

我想知道这种类型的关系(在 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 上的所有方法都没有有意义的实现

注意事项:

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

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

【问题讨论】:

    标签: swift generics swift-protocols associated-types


    【解决方案1】:

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

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

    请注意,Swift 的标准库现在包含一个名为 Result 的类型,因此您可能希望为您的 associatedtype 使用不同的名称。我在自己的代码中使用Answer

    associatedtype Answer: Sequence where Answer.Element == Value
    

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

    【讨论】:

    • 这真的很有趣。当然,这是有道理的。 Swift 团队为非 Objective-c 开发人员制定指南是明智的,因为语法与其他语言完全不同。
    • 这还能用吗?我得到“'A'不是'Self.Result'的成员类型”。
    • 实际上它从来没有工作过。我涉及Either 的示例有几个缺陷,因此我已将其删除。
    猜你喜欢
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    • 2021-09-21
    相关资源
    最近更新 更多