Why can't we compare optionals?
var x: Int?
x == 0 // ok
x > 0 // error
I found some explanation here (0121-remove-optional-comparison-operators):
but I fail to see why this example:
struct Pet {
let age: Int
}
struct Person {
let name: String
let pet: Pet?
}
let peeps = [
Person(name: "Fred", pet: Pet(age: 5)),
Person(name: "Jill", pet: .None), // no pet here
Person(name: "Burt", pet: Pet(age: 10)),
]
let ps = peeps.filter { $0.pet?.age < 6 }
ps == [Fred, Jill] // if you donāt own a pet, your non-existent pet is considered to be younger than any actual pet š¶
says "Fred, Jill" is returned (was it some gotcha of the previous implementation?). I would suppose that if $0.pet?.age < 6
was allowed it should have returned "false" for Jill, as if it was written:
`$0.pet?.age != nil && $0.pet!.age < 6` // or the better "if let" form
so the expected result would be [Fred].
Obviously instead of the currently disallowed x > 0
I can do:
x != nil && x! > 0
or its better "if let..." form. Or, at least conceptually, I can do "the equivalent":
x == 1 && x == 2 && x == 3 ..... && x == .max
It just looks odd that ==
and !=
is allowed but <
>
not. Perhaps I am missing some good example where optional comparison would be really surprising?
Note that the motivation section of the quoted article refers to some limitations in generics system which might be no longer applicable today.