[英]How do I implement Swift's Comparable protocol?
如何在 Swift 中使用 Comparable 協議? 在聲明中,它說我必須實現三個操作 <、<= 和 >=。 我把所有這些都放在課堂上,但它不起作用。 我還需要同時擁有這三個嗎? 因為應該可以從一個中推斷出所有這些。
Comparable 協議擴展了 Equatable 協議 -> 實現了兩者
在Apple 的參考中是來自 Apple 的一個示例(在 Comparable 協議參考中),您可以看到您應該如何做:不要將操作實現放在類中,而是放在外部/全局范圍內。 此外,您只需實現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
這是 Kametrixom 對Swift 3的回答的更新:
class Person : Comparable {
let name : String
init(name : String) {
self.name = name
}
static func < (lhs: Person, rhs: Person) -> Bool {
return lhs.name < rhs.name
}
static func == (lhs: Person, rhs: Person) -> Bool {
return lhs.name == rhs.name
}
}
然后可以將Person
類的實例與關系運算符進行比較,如下所示:
let paul = Person(name: "Paul")
let otherPaul = Person(name: "Paul")
let ben = Person(name: "Ben")
print(paul > otherPaul) // false
print(paul <= ben) // false
print(paul == otherPaul) // true
要實現 Swift 的Comparable
協議,首先需要通過實現static func == (lhs: Self, rhs: Self) -> Bool
來符合Equatable
協議,然后實現唯一需要的函數static func < (lhs: Self, rhs: Self) -> Bool
for Comparable
。
您應該在結構/類本身內實現符合協議的方法,而不是聲明全局運算符重載。 盡管全局運算符重載滿足協議一致性,但以這種方式聲明它們而不是結構/類上的預期靜態方法是不好的做法。
如果您查看文檔示例,您將看到與示例代碼相同。
我會寫以下內容:
class Person: Comparable {
let name: String
init(name: String) {
self.name = name
}
static func < (lhs: Person, rhs: Person) -> Bool {
return lhs.name < rhs.name
}
static func == (lhs: Person, rhs: Person) -> Bool {
return lhs.name == rhs.name
}
}
甚至將協議一致性從類聲明中分離出來,如下所示:
class Person {
let name: String
init(name: String) {
self.name = name
}
}
extension Person: Comparable {
static func < (lhs: Person, rhs: Person) -> Bool {
return lhs.name < rhs.name
}
static func == (lhs: Person, rhs: Person) -> Bool {
return lhs.name == rhs.name
}
}
這可能更接近生產級代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.