Checking the value of an Optional Bool

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

    I found another solution, overloading the Boolean operators. For example:

    public func <  (left: T?, right: T) -> Bool {
        if let left = left {
            return left < right
        }
        return false
    }
    

    This may not be totally in the "spirit" of the language changes, but it allows for safe unwrapping of optionals, and it is usable for conditionals anywhere, including while loops.

提交回复
热议问题