Most elegant way to compare two optionals in Swift
Assuming you're using Comparable entities, this will work on anything:
func optionalsAreEqual<T: Comparable>(firstVal: T?, secondVal: T?) -> Bool{
if let firstVal = firstVal, secondVal = secondVal {
return firstVal == secondVal
}
else{
return firstVal == nil && secondVal == nil
}
}
It's not exactly short and sweet, but it's expressive, clear, and reusable.
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")
}