Curnelious Curnelious - 1 year ago 49
Swift Question

Found nil for optional value?

I just can not figure this out :

let kind:NSString = module[Globals.sharedInstance.dataModuleName] as! NSString

Will print this, and then crash for strange reason :

( //dic print
meta = no;
module = IN;
subject = LT;
variable = A2;
module // print the right field we are looking for inside the dictionary .

fatal error: unexpectedly found nil while unwrapping an Optional value

But you can see that module is valid dictionary and also

Crashing on the line
let kind
. whats wrong with it ?

Answer Source

Your module is Array of Dictionary not directly Dictionary, so you need to first access its first object then the module key like this

let kind:String = module[0][Globals.sharedInstance.dataModuleName] as! String

Note: One sugeestion, in swift use String instead of NSString

Also you can use if let and guard with initializtion to avoid crash.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download