我正在尝试检查json响应的字典之一的空条件。但是当我检查条件时,出现类似的错误“二进制运算符'=='不能应用于类型的操作数'[[String:Any]'和'JSON'“ 。我在if !(chattt == JSON.null)
行遇到此错误。如果有人能帮助我解决此问题,那就太好了。谢谢! / p>
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)
}
}
}
答案 0 :(得分:1)
您可以这样做
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 let chattt = chat["chat"] as? [String:Any] else {
//Using this, the further code will never execute as implemented force return here
return
}
如果有任何问题,请告诉我。
答案 1 :(得分:0)
执行以下操作
guard let chattt = chat["chat"] as? [String:Any] else {
let viewc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ChatViewController") as? ChatViewController
self.navigationController?.pushViewController(viewc!, animated: true)
return
}