Snoobie
Snoobie

Reputation: 760

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,

Upvotes: 5

Views: 5311

Answers (3)

James Rochabrun
James Rochabrun

Reputation: 4377

So to answer your question in why you are getting that error, in your code "tmp" is not nil its something of type NSNull (if you want to know more about NSNull check the docs) but its basically "A singleton object used to represent null values in collection objects that don’t allow nil values." The rest is just you are force casting which I recommend avoiding this is a safer way to do what you are doing.

guard let objData = objJson["DATA"] as? [String: Any], let msg = objData["Message"] else { return }
// now you can use msg only if exists and also important keeping its unmutable state

Upvotes: 0

Ivan
Ivan

Reputation: 503

With Swift 3, for example:

fileprivate var rawNull: NSNull = NSNull()
public var object: Any {
   get {
      return self.rawNull
   }
}

You can check field object as:

if self.object is NSNull {
  // nil
}

Upvotes: 1

Ryan
Ryan

Reputation: 4884

You can add casting in let.

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

Upvotes: 4

Related Questions