Detect a Null value in NSDictionary Detect a Null value in NSDictionary ios ios

Detect a Null value in NSDictionary


You can use the as? operator, which returns an optional value (nil if the downcast fails)

if let latestValue = sensor["latestValue"] as? String {    cell.detailTextLabel.text = latestValue}

I tested this example in a swift application

let x: AnyObject = NSNull()if let y = x as? String {    println("I should never be printed: \(y)")} else {    println("Yay")}

and it correctly prints "Yay", whereas

let x: AnyObject = "hello!"if let y = x as? String {    println(y)} else {    println("I should never be printed")}

prints "hello!" as expected.


You could also use is to check for the presence of a null:

if sensor["latestValue"] is NSNull {    // do something with null JSON value here}


I'm using this combination and it also checks if object is not "null".

func isNotNull(object: AnyObject?) -> Bool {    guard let object = object else { return false }    return isNotNSNull(object) && isNotStringNull(object)}func isNotNSNull(object: AnyObject) -> Bool {    object.classForCoder != NSNull.classForCoder()}func isNotStringNull(object: AnyObject) -> Bool {    guard let object = object as? String where object.uppercaseString == "NULL" else {        return true    }    return false}

It's not that pretty as extension but work as charm :)