How to check if key exists in swiftyJSON when json contain array with no keys

Kocio picture Kocio · May 11, 2016 · Viewed 13.2k times · Source

I know about swiftyJSON method exists() but it does not seem to work always as they say. How can I get proper result in this case below? I cannot change JSON structure because I am getting this through client's API.

var json: JSON =  ["response": ["value1","value2"]]
if json["response"]["someKey"].exists(){
    print("response someKey exists")
}

Output:

response someKey exists

That shouldn't be printed because someKey does not exist. But sometimes that key comes from client's API, and i need to find out if it exists or not properly.

Answer

Eric Aya picture Eric Aya · May 11, 2016

It doesn't work in your case because the content of json["response"] is not a dictionary, it's an array. SwiftyJSON can't check for a valid dictionary key in an array.

With a dictionary, it works, the condition is not executed, as expected:

var json: JSON =  ["response": ["key1":"value1", "key2":"value2"]]
if json["response"]["someKey"].exists() {
    print("response someKey exists")
}

The solution to your issue is to check if the content is indeed a dictionary before using .exists():

if let _ = json["response"].dictionary {
    if json["response"]["someKey"].exists() {
        print("response someKey exists")
    }
}