'? Obviously the if responseValues["Custom" /> '? Obviously the if responseValues["Custom" /> '? Obviously the if responseValues["Custom"/>

How to check for <null> in Swift 5 and avoid 'NSInvalidArgumentException'?

670 views Asked by At

I'm using Swift 5.

Why does an NSInvalidArgumentException occur when responseValues["CustomerID"] == '<null>'?

Obviously the if responseValues["CustomerID"] is NSNull is not doing the trick. What check should be in place to avoid the NSInvalidArgumentException

self.api.getCustomerId(callback: { getIDResult in
  if let responseValues = getIDResult["ResponseValues"] {

    print("GET CUSTOMER ID RESULT")
    print(responseValues)

    if responseValues["CustomerID"] is NSNull { // <---- crashes here when null
        print("CustomerID is null")
    }
    else{
        print("CustomerID is NOT null")
    }
  }
})

Succesful result

GET CUSTOMER ID RESULT
{
    CustomerID = 403254;
}
CustomerID is NOT null

Crashing result when encountering a null customer id

GET CUSTOMER ID RESULT
{
    CustomerID = "<null>";
}

crashes with the following

019-11-21 12:13:16.819033-0500 MyApp[29412:4207932] -[NSNull _fastCStringContents:]: unrecognized selector sent to instance 0x7fff80615710
2019-11-21 12:13:16.820557-0500 MyApp[29412:4207932] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull _fastCStringContents:]: unrecognized selector sent to instance 0x7fff80615710'

Someone was questioning whether the value was actually null, here's some debug info on that dictionary:

enter image description here

1

There are 1 answers

6
Andres Gomez On

if responseValues is a dictionary, you can do this

if let customerId = responseValues["CustomerID"] as? String
{
   print(customerId)
}
else
{
   print("customer id isn't available")
}

if you want to know if is null, you have to change to Codable