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

后端 未结 1 572
一个人的身影
一个人的身影 2021-02-20 06: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

相关标签:
1条回答
  • 2021-02-20 06:45

    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")
        }
    }
    
    0 讨论(0)
提交回复
热议问题