Snoobie Snoobie - 18 days ago 11
Swift Question

How to check if a field type Any? is nil o NSNull

I'm actually trying to parse a Json object with Swift3 on Xcode8.1.
This is my code:

if let objData = objJson["DATA"] as! NSDictionary? {
var msg: String = ""
if let tmp = objData.object(forKey: "Message") {
msg = tmp as! String
} else {
print("NIIILLLLL")
}
}


I'm getting this error message:
Could not cast value of type 'NSNull' (0x4587b68) to 'NSString' (0x366d5f4)
at this line
msg = tmp as! String
.

I'm not understanding why I'm getting this error because the type of tmp is
Any
and it should display the print instead of convert
tmp as! String


Thank you for the help,

Answer

You can add casting in let.

if let tmp = objData.object(forKey: "Message") as? String { 
    msg = tmp
}