如何实现Swift的Comparable协议? [英] How do I implement Swift's Comparable protocol?
问题描述
如何在Swift中使用Comparable协议?在声明中说,我必须实现三个操作<,< =和> =。我把所有的那些在类,但它不工作。还需要我有三个人吗?
How do I use the Comparable protocol in Swift? In the declaration it says I'd have to implement the three operations <, <= and >=. I put all those in the class but it doesn't work. Also do I need to have all three of them? Because it should be possible to deduce all of them from a single one.
推荐答案
Comparable协议扩展了Equatable协议 - >实现两者
The Comparable protocol extends the Equatable protocol -> implement both of them
在 Apple's Reference 是来自Apple的一个示例(在Comparable协议参考中),您可以看到您应该如何做:不要将操作实现放在类中,而是放在外部/全局范围。此外,您只需要从可比较的
协议和 == 实现
<
code>从等于
协议。
In Apple's Reference is an example from Apple (within the Comparable protocol reference) you can see how you should do it: Don't put the operation implementations within the class, but rather on the outside/global scope. Also you only have to implement the <
operator from Comparable
protocol and ==
from Equatable
protocol.
正确的示例:
class Person : Comparable {
let name : String
init(name : String) {
self.name = name
}
}
func < (lhs: Person, rhs: Person) -> Bool {
return lhs.name < rhs.name
}
func == (lhs: Person, rhs: Person) -> Bool {
return lhs.name == rhs.name
}
let paul = Person(name: "Paul")
let otherPaul = Person(name: "Paul")
let ben = Person(name: "Ben")
paul > otherPaul // false
paul <= ben // false
paul == otherPaul // true
这篇关于如何实现Swift的Comparable协议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!