我正在尝试检查 json 响应的字典之一的空条件。但是当我检查条件时,我收到类似 “二元运算符‘==’无法应用于类型的操作数的错误'[String : Any]' 和 'JSON'”。我在 if !(chattt == JSON.null)
行收到此错误。如果有人帮助我解决这个问题,那就太好了。提前致谢。
let acce:String = UserDefaults.standard.string(forKey: "access-tokenn")!
print(acce)
let headers:HTTPHeaders = ["Authorization":"Bearer \(acce)","Content-Type":"application/X-Access-Token"]
print((Constants.Chatlistsearch)+(idd))
Alamofire.request((Constants.Chatlistsearch+idd), method: .get, encoding: URLEncoding.default, headers: headers).responseJSON { response in
switch response.result {
case .success:
//print(response)
if response.result.value != nil{
var maindictionary = NSDictionary()
maindictionary = response.result.value as! NSDictionary
// print(maindictionary)
var chat:Dictionary = maindictionary.value(forKey: "data") as! [String:Any]
// print(chat)
var chatt:Dictionary = chat["user"] as! [String:Any]
// print(chatt)
var chattt:Dictionary = chat["chat"] as! [String:Any]
print(chattt)
if !(chattt == JSON.null) {
let viewc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ChatViewController") as? ChatViewController
self.navigationController?.pushViewController(viewc!, animated: true)
}else{
print("Find Action")
}
// self.data = [String(stringInterpolationSegment: chatt["unique_id"])]
// print(self.data)
}
break
case .failure(let error):
print(error)
}
}
}
最佳答案
你可以这样做
if let chattt = chat["chat"] as? [String:Any] {
//It's available. Execute further tasks
} else {
//It's nil or chat["chat"] type is not dictionary.
}
您可以使用 guard 来完成。
guard let chattt = chat["chat"] as? [String:Any] else {
//Using this, the further code will never execute as implemented force return here
return
}
如果有任何问题,请告诉我。
关于ios - 如何检查 JSON 响应的空条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54901402/