使Swift协议符合相关类型的Equatable
在Swift 2.1(运行XCode 7.2)中,我试图使关联类型的协议符合Equatable使Swift协议符合相关类型的Equatable,swift,Swift,在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
// (#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)
///不会编译,为什么?
公共函数==(左侧:节点1,右侧:节点2)
{
返回lhs.content==rhs.content//错误:二进制运算符“==”不能应用于两个“Node1.content”操作数
}
在
#3
中,我们知道lhs和rhs都具有相同的类型,并且我们知道(从相关类型equalable
的规范可知,内容
是可均衡的。那么为什么我不能比较它们呢?添加->Bool
。只是一个错误消息。有时,跨多行编写函数声明并不能提高可读性
public func ==<Node1 : GraphNode, Node2 : GraphNode where Node1.Content == Node2.Content>(lhs: Node1, rhs: Node2) -> Bool {
return (lhs.content == rhs.content)
}
public func==(左:节点1,右:节点2)->Bool{
返回(lhs.content==rhs.content)
}
谢谢,就这样!有时,您只需要第二双眼睛(或者更好的编译错误报告:))