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

1

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?

Sepulture answered 27/11, 2014 at 12:36 Comment(0)
S
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

Shroud answered 27/11, 2014 at 12:49 Comment(4)
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. :(Bivouac
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?Shroud
Oh, it's my mistake. this error is raised with Implicitly Unwrapped Optional like var testNil: NSNumber! = nil. Sorry about it.Bivouac
Honestly you scared me for a moment :)Shroud

© 2022 - 2024 — McMap. All rights reserved.