9

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?

Zaggo
  • 786
  • 1
  • 6
  • 14

1 Answers1

17

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

Antonio
  • 71,651
  • 11
  • 148
  • 165
  • `testNil == true` raise `fatal error: unexpectedly found nil while unwrapping an Optional value`. So, you should write it like that `testNil?.boolValue == true`, if isn't looks good. :( – Wanbok Choi Apr 15 '15 at 12:02
  • I just tested that and it works correctly, no exception thrown. It's an optional, so no forced unwrapping occurs, so I wonder how you got that error. Is it possible you declared it as implicitly unwrapped optional by mistake? – Antonio Apr 15 '15 at 13:19
  • Oh, it's my mistake. this error is raised with Implicitly Unwrapped Optional like `var testNil: NSNumber! = nil`. Sorry about it. – Wanbok Choi Apr 15 '15 at 13:45
  • 1
    Honestly you scared me for a moment :) – Antonio Apr 15 '15 at 13:46