I'm trying to get data using JSON ad there is a null value causes crash.
let jsonData:NSDictionary = try NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary
let success:NSInteger = jsonData.valueForKey("success") as! NSInteger
//code error bad instruction
NSLog("Success: %ld", success);
how can I turn null to zero?
let success = (jsonData["success"] as? NSInteger) ?? 0
step by step:
jsonData["success"]
(please, don't use valueForKey
, it does something completely different)as? NSInteger
- try to cast it to NSInteger
or return nil
if it's not a number (in this case, it's a NSNull
instance)?? 0
- if nil
, use a default value of zero