Checking the value of an Optional Bool

后端 未结 6 527
情书的邮戳
情书的邮戳 2021-01-30 10:13

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:

6条回答
  •  时光说笑
    2021-01-30 10:32

    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

提交回复
热议问题