Evaluate Bool property of optional object in if statement

孤街浪徒 提交于 2020-01-10 14:20:51

问题


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
}

回答1:


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.




回答2:


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



回答3:


You could also do :

if let obj = objectWithBool where obj {
    // objectWithBool != nil && obj == true
} else {
   // objectWithBool == nil || obj == false
}


来源:https://stackoverflow.com/questions/26910229/evaluate-bool-property-of-optional-object-in-if-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!