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 arenil
true
if both have a value and the values are also equalfalse
otherwise
Is 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. :(