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 objec
Ah, found it:
if objectWithBool?.bool == true {
// objectWithBool != nil && bool == true
} else {
// objectWithBool == nil || bool == false
}
The optional chaining expression objectWithBool?.bool
returns an optional Bool
. Since it is optional, that expression alone in the if
statement would be evaluated to true
/false
based on whether the optional contains a value or not.
By using the ==
operator the if
statement checks the optional's value, which in this case can be true
, false
, or nil
.