【问题标题】:generics in swift protocolsswift 协议中的泛型
【发布时间】:2021-08-20 01:49:55
【问题描述】:

我正在尝试将访问者模式从我的(旧)java 代码迁移到 swift。到目前为止,我有一个通用的 FIFO(工作正常)。

protocol FiFo {
    associatedtype U
    func enqueue(_ : U)
    func dequeue() -> U
}

我还想告诉 FIFO 的实例只接受一个访问者的实例,该访问者使用与 FIFO 实例相同的泛型类型。

protocol Visitor {
    associatedtype T
    func processValue(_ value : T)
}
protocol FiFo {
    associatedtype U
    func enqueue(_ : U)
    func dequeue() -> U
    func visit(_ visitor : Visitor<U>)
}

我正面临着:

不能专门化非泛型类型“访客”

有什么提示吗?谢谢!

【问题讨论】:

  • 泛型和关联类型是两个不同的东西。
  • 感谢您的回答 - 我很乐意将两者都标记为有帮助。并感谢泛型与关联类型之间存在差异的一般提示(快速)。
  • 这能回答你的问题吗? How to create generic protocols in Swift?
  • @RTXGamer:重新编辑:反引号用于code,不用于一般强调。 “访客模式”或“fifo”不是代码。
  • @pkamb:我发现了另一个问题,但我完全不确定如何将该解决方案应用于两个协议的问题。 where 出现的部分在另一篇文章中对我来说不是很清楚。

标签: swift protocols


【解决方案1】:

您可以将visit 方法设为泛型:接受其关联类型T 是fifo 的类型U 的任何访问者:

protocol FiFo {
    associatedtype U
    func enqueue(_ : U)
    func dequeue() -> U
    func visit<V: Visitor>(_ visitor : V) where V.T == U
}

【讨论】:

    【解决方案2】:

    您可以为关联类型添加约束:

    protocol Visitor {
        associatedtype T
        func processValue(_ value : T)
    }
    
    protocol FiFo {
        associatedtype U
        associatedtype V: Visitor where V.T == U
        func enqueue(_ : U)
        func dequeue() -> U
        func visit(_ visitor: V)
    }
    

    【讨论】:

    • 对不起,我没有看到你的答案出现。现在我想知道我们的建议之间是否存在差异,或者它们是否相同。
    • @MartinR - 不用担心。重新区分 b/w 泛型和关联类型,这是标准的同质与异质问题:例如,如果有多个 FiFo 方法采用 Visitor,有多个带有 where V.T == U 的方法,它们不会必须是相同的类型,而关联类型可以强制执行)。如果它真的只是Visitor 的一种泛型方法,那么你的泛型模式更简洁。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-09
    • 1970-01-01
    • 2014-09-10
    相关资源
    最近更新 更多