Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does anybody know the rationale behind "(nil < 0) == true" and "(nil <= 0) == true" in Swift?

Tags:

null

swift

swift2

I think that Swift is a very well constructed modern language, however, there is one thing that puzzle me, and that is the rationale for having (nil <= 0) == true and (nil < 0) == true.

Here are more cases:

enter image description here

Anyway, return true for nil < 0 seems to go against the whole optional concept, where one of the argument was about avoiding the default number initialization to "0". Now "0" is special again.

Anybody has any explanation Swift decided to have (nil <= 0) and (nil < 0) return true.

like image 423
Jeremy Chone Avatar asked Jul 16 '15 17:07

Jeremy Chone


2 Answers

Optionals are comparable, so they can be sorted, for example. The rules are very simple:

  1. Any two optionals that are nil compare equal.
  2. If one of the optionals is nil and the other is not, nil is less than non-nil.
  3. If both optionals are not nil, then the unwrapped values are compared.

As a consequence, nil equals nil, and nil is less than any non-nil optional.

It has nothing to do with the value 0 that you assigned. Assign -1000, or +100, or whatever you like, and you get the same result.

like image 110
gnasher729 Avatar answered May 18 '23 17:05

gnasher729


When comparing two optionals when one is nil and the other some value, the value is always 'bigger' because there isn't nothing.

So

nil < 0 = true     Because 0 is some value but nil isn't
nil == 0 = false    Makes sense because 0 isn't nil
nil <= 0 = true    Same as before

0 can also be replaced with any value and the same result would be produced. Actually the function

func < <T>(lhs: T?, rhs: T?) -> Bool

Doesn't even look at the underlying value if one of them is nil, it just says: Some value is bigger than no value and No value is equal to no value

like image 44
Kametrixom Avatar answered May 18 '23 17:05

Kametrixom