Get the negative of an Optional Chain

2019-07-11 01:04发布

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?

3条回答
小情绪 Triste *
2楼-- · 2019-07-11 01:13

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")
}
查看更多
男人必须洒脱
3楼-- · 2019-07-11 01:32

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.

查看更多
干净又极端
4楼-- · 2019-07-11 01:32

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

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

    //your code

}
查看更多
登录 后发表回答