Search code examples
crashswift2ios9do-catch

app crashes because of null values, swift 2


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?


Solution

  • let success = (jsonData["success"] as? NSInteger) ?? 0
    

    step by step:

    1. get the value jsonData["success"] (please, don't use valueForKey, it does something completely different)
    2. 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)
    3. ?? 0 - if nil, use a default value of zero