Reputation: 5397
Optional values unlike nil / NULL cannot by default be compared with numerical values. What steps must be taken to have e.g. nil < 1
and nil < 1.0
evaluate to true?
Upvotes: 1
Views: 119
Reputation: 11
I'm not sure I would recommend doing this, but you could do something like this, as an example for integers to first check if it's nil and if so just compare with 0. You would have to repeat this thing for flipped parameters and the same thing for other types.
extension Optional where Wrapped == Comparable {
public static func < (lhs: Wrapped?, rhs: Int) -> Bool {
guard let left = lhs as? Int else {
return 0 < rhs
}
return left < rhs
}
}
Upvotes: 1
Reputation: 299623
nil == 0
will never evaluate to true because it is false. Similarly 1 == 0
will not evaluate to true, and there are no reasonable steps you can take to make it do so. Unequal things should not return true for ==
.
The syntax you want is (nil ?? 0) == 0
, which is true.
But if you find yourself trying to treat nil as 0 very often (often enough that you would want some special handling), then that suggests your type is incorrect. Why is this variable Optional? It sounds like this variable should be just an Int in the first place. If it comes into your system as Optional (most commonly via JSON), you should convert it to a non-Optional type as early as you can and use that throughout the rest of the system. The vast majority of variables and properties in Swift should not be Optional. If they are (and many people make this mistake), you will find yourself fighting the system constantly.
To your edit, Swift used to allow you to use <
with nil this way. It was removed on purpose (SE-0121) because it causes so many really subtle bugs (just like treating NULL implicitly as 0 has long caused bugs in C and ObjC). You definitely should not try to put that back in. It's a really bad semantic.
Upvotes: 1