Accessing boolValue in a NSNumber var with optional chaining (in Swift)

Zaggo picture Zaggo · Nov 27, 2014 · Viewed 7k times · Source

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?

Answer

Antonio picture Antonio · Nov 27, 2014

You can just compare it to a boolean value:

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's true
}

if testTrue == true {
    // It's true
}

if testNil == true {
    // not true
}

if testInteger == true {
    // not true
}

The most interesting thing is that 1 is recognized as true - which is expected, because the type is NSNumber