在Swift中符合Comparable的泛型类 [英] Generic class that conforms to Comparable in Swift
问题描述
我试图创建一个符合Comparable协议的简单通用节点类,以便我可以在不访问密钥的情况下轻松比较节点。当我尝试写入<和==功能,但是,编译器似乎不喜欢它。 <和==函数在定义Node参数时需要一个类型。这在Java中很简单,您定义了平等和<内部向班级。 Swift在全球范围内寻求它。任何想法?
I'm attempting to create a simple generic node class that conforms to the Comparable protocol so that I can easily compare nodes without accessing their key. When I attempt to write the < and == functions, however, the compiler doesn't seem to like it. The < and == functions expect a type when defining the Node parameters. This was simple in Java where you defined equality and < internally to the class. Swift asks for it globally. Any thoughts ?
示例:
Example:
func < (lhs:Node<E:Comparable>, rhs:Node<E:Comparable>) -> Bool {
return lhs.key < rhs.key
}
func == (lhs:Node<E:Comparable>, rhs:Node<E:Comparable>) -> Bool {
return lhs.key == rhs.key
}
class Node<D:Comparable>: Comparable {
var key: D!
var next:Node?
var prev:Node?
init( key:D ) {
self.key = key
}
}
推荐答案
你很近! Node类已经指定对于 Node
, D
必须符合 Comparable
。因此, ==
和 <<
中的
节点< E:Comparable> / code>是多余的。相反,您希望限制可以调用操作符的类型:
You're close! The Node class already specifies that for Node<D>
, D
must conform to Comparable
. Therefore, Node<E: Comparable>
in the decl for ==
and <
is redundant. Instead, you want to restrict the types that the operators can be invoked upon:
func < <E: Comparable>(lhs: Node<E>, rhs: Node<E>) -> Bool {
return lhs.key < rhs.key
}
func == <E: Comparable>(lhs: Node<E>, rhs: Node<E>) -> Bool {
return lhs.key == rhs.key
}
class Node<D: Comparable>: Comparable {
var key: D!
var next: Node?
var prev: Node?
init(key: D) {
self.key = key
}
}
这篇关于在Swift中符合Comparable的泛型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!