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.”
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With