Get the negative of an Optional Chain

2019-07-11 00:42发布

问题:

This is not allowed (bad expression)

if !(let nsDictionaryObject = swiftObject as? NSDictionary)
{
    "Error could not make NSDictionary in \(self)"
    return
}

Is it possible to check for the negative of an Optional Chain expression in 1 line?

回答1:

In Swift 2.0, you can use

guard let nsDictionaryObject = swiftObject as? NSDictionary else {
    "Error could not make NSDictionary in \(self)"
    return
}

This will also bind nsDictionaryObject to the scope outside the guard statement.



回答2:

If you are using swift 1.2 you can do it this way:

if let nsDictionaryObject = swiftObject as? NSDictionary{} else {

    //your code

}


回答3:

In Swift 1 you could, for instance, use the else branch or check for a nil result.

var swiftObject: AnyObject = ""

if let _ = swiftObject as? NSDictionary { } else {
    println("error")
}

if swiftObject as? NSDictionary == nil {
    println("error")
}