【发布时间】: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.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
}
在#3 中,我们知道 lhs 和 rhs 具有相同的类型,并且我们知道(从关联类型为 Equatable 的规范中)Content 是等价的。那么为什么我不能比较它们呢?
【问题讨论】:
标签: swift