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.

推荐答案

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

Swift相关问答推荐

如何避免使用DispatchSemaphores时线程爆炸?

动画过程中的SwiftUI重绘视图

如何在DATE()中进行比较

SWIFT`String.Encoding`:`.unicode`vs`.utf16`

如何观察UIViewRepresentable中的多个变化?

为什么我不能在这个 Swift 间接枚举中返回 self ?

UIView.convert(_ point:to:)的意外行为

在表单中对齐文本框

为什么 UITapGestureRecognizer 对于 Swift 集合视图中的单元格图像无法正常工作?

Swift // Sprite Kit:类别位掩码限制

Swift 并发:@MainActor 对象上的通知回调

XCUITest 在 TearDown 期间随机失败-无法终止 com.bundle.id

为什么 Apple Scrumdinger Sample App 使用两个事实来源?

用户输入以更改通过点击生成的形状大小

如何将使用\u{ea12}创建的 Swift 字符串转换回其十六进制值/字符串ea12?

Swift 函数 vs 惰性变量 vs 计算(computed)属性 - 区别?

Swift 动画 WithDuration 语法是什么?

Swift 中的 PageViewController 当前页面索引

更改日期 Select 器的文本 colored颜色

协议扩展中的where self是什么