使Swift协议符合相关类型的Equatable

时间:2023-01-23 22:19:36

In Swift 2.1 (running XCode 7.2), I am trying to have a Protocol with associated type conform to Equatable.

在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}
}

As we could have non-homogeneous implementations of the protocol that define a different type for the associated type, I expect that I won't be able to define here (at the protocol level, not at the implementation level) an equality function:

由于我们可以为协议定义不同类型的协议的非同类实现,我希望我不能在这里定义(在协议级别,而不是在实现级别)一个相等的函数:

// (#2)

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

This is because I have no guarantee that lhs.Content is the same type as rhs.Content. However I was hoping I could specify it with some generic constraint, such as:

这是因为我无法保证lhs.Content与rhs.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
}

In #3, we know that both lhs and rhs have the same type, and we know (from the specification of the associated type as Equatable) that Content is equatable. So why can't I compare them?

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

1 个解决方案

#1


1  

Add -> Bool. Just a bad error message. Sometimes writing function declaration across multiple lines doesn't make it more readable.

添加 - > Bool。只是一个错误的错误消息。有时在多行中编写函数声明并不会使其更具可读性。

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

    return (lhs.content == rhs.content)

}

#1


1  

Add -> Bool. Just a bad error message. Sometimes writing function declaration across multiple lines doesn't make it more readable.

添加 - > Bool。只是一个错误的错误消息。有时在多行中编写函数声明并不会使其更具可读性。

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

    return (lhs.content == rhs.content)

}