I have two AnyObject?
variables that I would like to compare for reference equality:
var oldValue: AnyObject?
var newValue: AnyObject?
...
if oldValue != newValue {
changed = true
}
This doesn't work though, as I apparently cannot compare two optionals directly. I want the behavior as if I were comparing id
s in Objective-C, that is:
true
if both are nil
true
if both have a value and the values are also equalfalse
otherwiseIs there an elegant way to write this in Swift (ideally without having to write a custom extension)?
This is the best I've come up with:
if !(oldValue != nil && newValue != nil && oldValue == newValue)
Not very pretty. :(
You can use !==
From The Swift Programming Language
Swift also provides two identity operators (
===
and!==
), which you use to test wether two objects references both refer to the same object instance.
Some good examples and explanations are also at Difference between == and ===
On @PEEJWEEJ point, doing the following will result in false
var newValue: AnyObject? = "String"
var oldValue: AnyObject? = "String"
if newValue === oldValue {
print("true")
} else {
print("false")
}