Curnelious Curnelious - 1 year ago 78
Swift Question

Reading a nil value from dictionary key?

I get a crash when I read a value from dictionary that is not there , so :

let state:NSString = module["state"] as! NSString

is crashing,because I need the
? or !
, so if i try to :

let state:NSString = module!["state"] as! NSString
let state:NSString = module?["state"] as! NSString

I get an error from compiler that I have to remove the

So how you do that correctly ?

Answer Source

You'll want to use optional binding.

if let state = module["state"] as? NSString {
  // do something with state

// else the value was nil

Or, as suggested in the comments, you can use a guard statement.

guard let state = module["state"] as? NSString else {
    // handle nil value
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download