Curnelious Curnelious - 4 months ago 10
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
//or
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

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
    return
}