I have a NSManagedObject subclass with an optional instance variable
@NSManaged var condition: NSNumber? // This refers to a optional boolean value in the data model
I'd like to do something when the condition variable exists and contains 'true'.
Of course, I can do it like this:
if let cond = condition {
if cond.boolValue {
// do something
}
}
However, I hoped it would be possible to do the same thing a little bit more compact with optional chaining. Something like this:
if condition?.boolValue {
// do something
}
But this produces a compiler error:
Optional type '$T4??' cannot be used as a boolean; test for '!= nil' instead
The most compact way to solve this problem was this:
if condition != nil && condition!.boolValue {
// do something
}
Is there really no way to access the boolean value with optional chaining, or am I missing something here?
testNil == true
raisefatal error: unexpectedly found nil while unwrapping an Optional value
. So, you should write it like thattestNil?.boolValue == true
, if isn't looks good. :( – Bivouac