The Comparable protocol extends the Equatable protocol -> implement both of them
在Apple's Reference中有一个苹果的例子(在可比较的协议参考中),你可以看到你应该如何做:不要把操作实现放在类内,而是放在外部/全局范围内.此外,您只需实现Comparable
协议中的<
运算符和Equatable
协议中的==
运算符.
正确的例子:
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