Checking the value of an Optional Bool

后端 未结 6 535
情书的邮戳
情书的邮戳 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:35

    The answer I found most easy to read is to define a function. Not very complicated but does the work.

    func isTrue(_ bool: Bool?) -> Bool {
        guard let b = bool else {
            return false
        }
        return b
    }
    

    usage:

    let b: Bool? = true
    if isTrue(b) {
        // b exists and is true
    } else {
        // b does either not exist or is false
    }
    

提交回复
热议问题