Checking the value of an Optional Bool

Moon Cat picture Moon Cat · Aug 27, 2014 · Viewed 68.2k times · Source

When I want to check if an Optional Bool is true, doing this doesn't work:

var boolean : Bool? = false
if boolean{
}

It results in this error:

Optional type '@IvalueBool?' cannot be used as a boolean; test for '!= nil' instead

I don't want to check for nil; I want to check if the value returned is true.

Do I always have to do if boolean == true if I'm working with an Optional Bool?

Since Optionals don't conform to BooleanType anymore, shouldn't the compiler know that I want to check the value of the Bool?

Answer

Antonio picture Antonio · Aug 27, 2014

With optional booleans it's needed to make the check explicit:

if boolean == true {
    ...
}

Otherwise you can unwrap the optional:

if boolean! {
    ...
}

But that generates a runtime exception if boolean is nil - to prevent that:

if boolean != nil && boolean! {
    ...
}

Before beta 5 it was possible, but it has been changed as reported in the release notes:

Optionals no longer implicitly evaluate to true when they have a value and false when they do not, to avoid confusion when working with optional Bool values. Instead, make an explicit check against nil with the == or != operators to find out if an optional contains a value.

Addendum: as suggested by @MartinR, a more compact variation to the 3rd option is using the coalescing operator:

if boolean ?? false {
    // this code runs only if boolean == true
}

which means: if boolean is not nil, the expression evaluates to the boolean value (i.e. using the unwrapped boolean value), otherwise the expression evaluates to false