【问题标题】:Make Swift protocol conform to Equatable on associated type使 Swift 协议在关联类型上符合 Equatable
【发布时间】:2016-01-24 11:10:18
【问题描述】:

在 Swift 2.1(运行 XCode 7.2)中,我试图让关联类型的协议符合 Equatable。

// (#1)

/**
A Node in a graph
*/
public protocol GraphNode : Equatable {

    typealias Content : Equatable

    /**
     The content of the node.
     E.g. in a graph of strings, this is a string
     */
    var content: Content {get}

    /// The list of neighbours of this Node in the graph
    var children: [Self] {get}
}

由于我们可能有为关联类型定义不同类型的协议的非同质实现,我希望我无法在此处(在协议级别,而不是在实现级别)定义相等功能:

// (#2)

/// Won't compile, as expected
public func ==(lhs: GraphNode, rhs: GraphNode) {
    return lhs.content == rhs.content
}

这是因为我无法保证lhs.Contentrhs.Content 的类型相同。 但是我希望我可以使用一些通用约束来指定它,例如:

// (#3)

/// Won't compile, why?
public func ==<Node1 : GraphNode, Node2 : GraphNode where Node1.Content == Node2.Content>(lhs: Node1, rhs: Node2) 
{
    return lhs.content == rhs.content  // ERROR: Binary operator '==' cannot be applied to two 'Node1.Content' operands
}

#3 中,我们知道 lhs 和 rhs 具有相同的类型,并且我们知道(从关联类型为 Equatable 的规范中)Content 是等价的。那么为什么我不能比较它们呢?

【问题讨论】:

    标签: swift


    【解决方案1】:

    添加-&gt; Bool。只是一个糟糕的错误消息。有时跨多行编写函数声明并不能使其更具可读性。

    public func ==<Node1 : GraphNode, Node2 : GraphNode where Node1.Content == Node2.Content>(lhs: Node1, rhs: Node2) -> Bool {
    
        return (lhs.content == rhs.content)
    
    }
    

    【讨论】:

    • 谢谢,就是这样!有时您只需要第二双眼睛(或更好的编译错误报告:))
    猜你喜欢
    • 2022-08-02
    • 2020-12-04
    • 2016-09-29
    • 1970-01-01
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多