Evaluate Bool property of optional object in if statement

后端 未结 3 1676
失恋的感觉
失恋的感觉 2020-12-31 13:11

I am looking for a way to evaluate a Swift Bool concisely in a single if statement, when the Bool is the property of an optional objec

相关标签:
3条回答
  • 2020-12-31 13:23

    Ah, found it:

    if objectWithBool?.bool == true {
        // objectWithBool != nil && bool == true
    } else {
        // objectWithBool == nil || bool == false
    }
    

    The optional chaining expression objectWithBool?.bool returns an optional Bool. Since it is optional, that expression alone in the if statement would be evaluated to true/false based on whether the optional contains a value or not.

    By using the == operator the if statement checks the optional's value, which in this case can be true, false, or nil.

    0 讨论(0)
  • 2020-12-31 13:26

    You could also do :

    if let obj = objectWithBool where obj {
        // objectWithBool != nil && obj == true
    } else {
       // objectWithBool == nil || obj == false
    }
    
    0 讨论(0)
  • 2020-12-31 13:39

    Another possible solution is:

    if objectWithBool?.bool ?? false {
        println("objectWithBool != nil && objectWithBool.bool == true")
    } else {
        println("objectWithBool == nil || objectWithBool.bool == false")
    }
    

    The "nil coalescing operator" a ?? b is a shorthand for

    a != nil ? a! : b
    
    0 讨论(0)
提交回复
热议问题