Search code examples
swiftoption-type

Most elegant way to compare two optionals in Swift


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 ids in Objective-C, that is:

  • true if both are nil
  • true if both have a value and the values are also equal
  • false 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. :(


Solution

  • 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")
    }