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

坚强是说给别人听的谎言 提交于 2019-12-21 07:36:09

问题


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.


回答1:


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")
    }
}


来源:https://stackoverflow.com/questions/37167618/how-to-check-if-key-exists-in-swiftyjson-when-json-contain-array-with-no-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!