Access boolValue in NSNumber var with optional binding (in Swift)

I have a subclass of NSManagedObject with an optional instance variable

@NSManaged var condition: NSNumber? // This refers to a optional boolean value in the data model 

I would 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 was hoping that it would be possible to do the same a little more compactly with the optional chain. Something like that:

 if condition?.boolValue { // do something } 

But this causes a compiler error:

Additional type '$ T4 ??' cannot be used as logical; test instead of '! = nil'

The most compact way to solve this problem:

 if condition != nil && condition!.boolValue { // do something } 

Is there no way to access a boolean with an optional chain, or am I missing something here?

+7
swift optional nsnumber
source share
1 answer

You can simply compare it to a boolean:

 if condition == true { ... } 

Some test cases:

 var testZero: NSNumber? = 0 var testOne: NSNumber? = 1 var testTrue: NSNumber? = true var testNil: NSNumber? = nil var testInteger: NSNumber? = 10 if testZero == true { // not true } if testOne == true { // it true } if testTrue == true { // It true } if testNil == true { // not true } if testInteger == true { // not true } 

Most interestingly, 1 recognized as true - which is expected because the type is NSNumber

+14
source share

All Articles