问题描述
如何在 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 协议参考中)你可以看到你应该怎么做:不要把操作实现放在类中,而是放在外部/全局范围内.此外,您只需实现 Comparable
协议中的 <
运算符和 Equatable
协议中的 ==
运算符.
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 协议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!