I am looking for a way to evaluate a Swift Bool concisely in a single if statement, when the Bool is the property of an optional object:
var objectWithBool: ClassWithBool?
// ...
if let obj = objectWithBool {
if obj.bool {
// bool == true
} else {
// bool == false
}
} else {
// objectWithBool == nil
}
Is there are way to combine these if statements? In Objective-C this could easily be done, as a nil object can be evaluated in the same expression:
if (objectWithBool.bool) {
// bool == true
} else {
// bool == false || objectWithBool == nil
}
Ah, found it:
The optional chaining expression
objectWithBool?.boolreturns an optionalBool. Since it is optional, that expression alone in theifstatement would be evaluated totrue/falsebased on whether the optional contains a value or not.By using the
==operator theifstatement checks the optional's value, which in this case can betrue,false, ornil.