Why can't Swift's greater-than or less-than operators compare optionals when the equality operators can?

前端 未结 3 870
温柔的废话
温柔的废话 2020-11-30 15:01

In Swift 3, this is a compile error, if I use > or <

let a: Int?
guard a > 0 else {return}
guard a < 0 else {return}
         


        
3条回答
  •  时光说笑
    2020-11-30 15:59

    Optional equality works logically, comparison doesn't.

    • 5 == 5 = true
    • 5 == nil = false
    • 5 == 6 = false
    • nil == nil = true

    Those all make sense, but these don't:

    • 6 > 5 = true
    • 5 > 5 = false
    • 5 > nil = ??
    • nil > 5 = ??

    This type of comparison does not have a simple answer, nor will that answer be the same depending on the use case.

提交回复
热议问题