Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

swift3

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,

like image 514
Snoobie Avatar asked Nov 18 '16 23:11

Snoobie


People also ask

How do you check if an object is NSNull?

We can use NSNull to represent nil objects in collections, and we typically see NSNull when we convert JSON to Objective-C objects and the JSON contained null values. Our preferred way to check if something is NSNull is [[NSNull null] isEqual:something] .

How check object is nil or not in Swift?

In Swift, you can also use nil-coalescing operator to check whether a optional contains a value or not. It is defined as (a ?? b) . It unwraps an optional a and returns it if it contains a value, or returns a default value b if a is nil.

IS NULL same as nil?

NULL and nil are equal to each other, but nil is an object value while NULL is a generic pointer value ((void*)0, to be specific). [NSNull null] is an object that's meant to stand in for nil in situations where nil isn't allowed. For example, you can't have a nil value in an NSArray.

How do you check if a value is null in Swift?

Swift – Check if Variable is not nil If optional variable is assigned with nil , then this says that there is no value in this variable. To check if this variable is not nil, we can use Swift Inequality Operator !=


2 Answers

You can add casting in let.

if let tmp = objData.object(forKey: "Message") as? String { 
    msg = tmp
}
like image 153
Ryan Avatar answered Nov 15 '22 06:11

Ryan


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
}
like image 42
Ivan Avatar answered Nov 15 '22 08:11

Ivan