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

Koc*_*cio 11 json ios swift swifty-json

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")
}
Run Code Online (Sandbox Code Playgroud)

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.

aya*_*aio 26

它在你的情况下不起作用,因为它的内容json["response"]不是字典,而是一个数组.SwiftyJSON无法检查数组中的有效字典键.

使用字典,它可以工作,条件不会按预期执行:

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

您的问题的解决方案是在使用之前检查内容是否确实是字典.exists():

if let _ = json["response"].dictionary {
    if json["response"]["someKey"].exists() {
        print("response someKey exists")
    }
}
Run Code Online (Sandbox Code Playgroud)