Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking the value of an Optional Bool

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?

like image 945
Moon Cat Avatar asked Aug 27 '14 09:08

Moon Cat


People also ask

What are the possible values for a bool value?

It has two possible values: True and False , which are special versions of 1 and 0 respectively and behave as such in arithmetic contexts.

Can bool be nil?

You can't. A BOOL is either YES or NO . There is no other state.

What is the value of bool false?

There are just two values of type bool: true and false. They are used as the values of expressions that have yes-or-no answers. C++ is different from Java in that type bool is actually equivalent to type int. Constant true is 1 and constant false is 0.

Is bool true 1 or 0?

C does not have boolean data types, and normally uses integers for boolean testing. Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true.


1 Answers

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

like image 183
Antonio Avatar answered Oct 05 '22 00:10

Antonio