Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate Bool property of optional object in if statement

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 object:

var objectWithBool: ClassWithBool?
// ...

if let obj = objectWithBool {
    if obj.bool {
        // bool == true
    } else {
        // bool == false
    }
} else {
    // objectWithBool == nil
}

Is there are way to combine these if statements? In Objective-C this could easily be done, as a nil object can be evaluated in the same expression:

if (objectWithBool.bool) {
    // bool == true
} else {
    // bool == false || objectWithBool == nil
}
like image 577
Stuart Avatar asked Nov 13 '14 13:11

Stuart


People also ask

How do you know if Boolean is optional?

Optional binding The code let booleanValue = booleanValue returns false if booleanValue is nil and the if block does not execute. If booleanValue is not nil , this code defines a new variable named booleanValue of type Bool (instead of an optional, Bool? ).

Can bool be nil Swift?

Nil is not a Bool. phoneyDev: The error states that the Bool? has not been unwrapped. That's what optional chaining does.

How do you declare a boolean variable in Swift?

Swift recognizes a value as boolean if it sees true or false . You can implicitly declar a boolean variable let a = false or explicitly declare a boolean variable let i:Bool = true .


2 Answers

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.

like image 199
Stuart Avatar answered Oct 24 '22 14:10

Stuart


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
like image 34
Martin R Avatar answered Oct 24 '22 14:10

Martin R