Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift === with nil

Tags:

swift

Why does the following not work in Swift?

if someObject === nil {
}

You have to do the test using the == operator such as

if someObject == nil {
}

I was thinking that === was more like making sure the instances where the exact same (basically comparing the pointers) and == was more like an isEqual check. Thus I would think === would be more appropriate for testing against nil, but I am obviously incorrect.

The documentation states:

=== or “Identical to” means that two constants or variables of class type refer to exactly the same class instance.

== or “Equal to” means that two instances are considered “equal” or “equivalent” in value, for some appropriate meaning of “equal”, as defined by the type’s designer.”

like image 447
Tod Cunningham Avatar asked Jun 19 '14 19:06

Tod Cunningham


1 Answers

It works exactly like you expect:

var s: String? = nil
s === nil // true

The only caveat is that to compare to nil, your variable must able to be nil. This means that it must be an optional, denoted with a ?.

var s: String is not allowed to be nil, so would therefore always returns false when === compared to nil.

like image 135
Alex Wayne Avatar answered Sep 23 '22 05:09

Alex Wayne