Search code examples
iosswiftoptional-chaining

Get the negative of an Optional Chain


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?


Solution

  • 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.