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.


The error is due to assuming (force casting) a value that can sometimes be nil. Swift is awesome, because it allows conditional unwraps and conditional casts in very concise statements. I recommend the following (for Swift 1-3):

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at


Login to comment


TOP Ranking