[英]How to check if key exists in swiftyJSON when json contain array with no keys
我知道swiftyJSON方法exists()但它似乎並不總是如他們所說。 在下面這種情況下如何獲得正確的結果? 我無法更改JSON結構,因為我通過客戶端的API獲取此信息。
var json: JSON = ["response": ["value1","value2"]]
if json["response"]["someKey"].exists(){
print("response someKey exists")
}
輸出:
response someKey exists
不應該打印,因為someKey不存在。 但有時候這個密鑰來自客戶端的API,我需要找出它是否存在。
它在你的情況下不起作用,因為json["response"]
內容不是字典,它是一個數組。 SwiftyJSON無法檢查數組中的有效字典鍵。
使用字典,它可以工作,條件不會按預期執行:
var json: JSON = ["response": ["key1":"value1", "key2":"value2"]]
if json["response"]["someKey"].exists() {
print("response someKey exists")
}
您的問題的解決方案是在使用.exists()
之前檢查內容是否確實是字典:
if let _ = json["response"].dictionary {
if json["response"]["someKey"].exists() {
print("response someKey exists")
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.