Get the negative of an Optional Chain

匆匆过客 提交于 2019-12-11 04:06:07

问题


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")
}


来源:https://stackoverflow.com/questions/32003983/get-the-negative-of-an-optional-chain

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