MantasG MantasG - 5 months ago 71x
Swift Question

How to check if NSDictionary is not nil in Swift 2

I'm getting NSDictionary as parameter in my function but having problem because don't know how to check if that parameter is not nil.

My function looks like this:

func doSmth(val : NSDictionary)

Inside my function I'm trying to get some values:

let action = val["action"] as! String

But getting error "fatal error: unexpectedly found nil while unwrapping an Optional value" when receive parameter val as nil.


Use if let to conditionally check for "action" in the dictionary. Use as? to conditionally cast the value to a String

if let actionString = val["action"] as? String {
   // action is not nil, is a String type, and is now stored in actionString
} else {
   // action was either nil, or not a String type