6

I am parsing a JSON response and trying to check if one of my keys is null. How would I go about this? I have the following:

var routingNumber = (dic.value(forKey: "result") as! NSDictionary).value(forKey: "routingNumber") as! String

and this returns:

Could not cast value of type 'NSNull' (0x107d238c8) to 'NSString' (0x107329c40).

How would I check if the value is NSNULL?

if( something != NSNULL){
    do something
}else{
    do something else
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
user2423476
  • 2,115
  • 8
  • 28
  • 40
  • if let routingNumber = (dic["result"] as? [String: Any])?["routingNumber"] as? String { } – Suen Feb 23 '17 at 05:23
  • Do not use `NSDictionary` in Swift. Use a Swift dictionary. Do not use `value(forKey:)` to get a value unless you have a specific reason to be using KVC (which you don't have in this case). – rmaddy Feb 23 '17 at 05:59
  • Wy not use the Swift dictionary? – Brandon A Jun 21 '17 at 20:20

4 Answers4

11

You can extract value from dic like this.

if let value = (dict["key"] as? String) 
{ 
  //NOT NULL
} 
else 
{
   //NULL
}
Rocky Balboa
  • 784
  • 10
  • 25
Amit Singh
  • 172
  • 1
  • 12
6

create below function

func isNsnullOrNil(object : AnyObject?) -> Bool
{
    if (object is NSNull) || (object == nil)
    {
        return true
    }
    else
    {
        return false
    }
}

call function where you want to check for null or nil value

if isNsnullOrNil((dic.value(forKey: "result") as! NSDictionary).value(forKey: "routingNumber"))
{
    print("object is null or nil")
}
else
{
    print("object is not  null or nil")
}
Rajesh73
  • 342
  • 1
  • 6
  • 16
Chetan Hedamba
  • 229
  • 2
  • 7
0

I had this same problem once.

CHECK FOR IF NSNULL

if let result = dic["result"] as? NSDictionary {
    // There is a dictionary

    if let routingNumber = result["routingNumber"] as? String {
         // There is a routingNumber
    }
    else if let routingNumber = result["routingNumber"] as? NSNull {
         // There is routingNumber but Null
    }
    else {
        // No routingNumber
    }
} 

That should do the trick.

Brandon A
  • 8,153
  • 3
  • 42
  • 77
0
if let result = dict["result"] as? [String:Any], let routingNumber = result["routingNumber"] as? String { 
    print("the routingNumber is \(routingNumber)")
} else { 
    print("nil") 
}
Rajesh73
  • 342
  • 1
  • 6
  • 16
Ram
  • 961
  • 6
  • 14