我创建了一个类,当我尝试将对象转换为AnyObject时收到警告消息。 警告是:“从'Any'到'AnyObject'的条件转换始终成功” 如何从文件中删除此警告?
这是我的代码:
class WebServices
{
class func getRequest( urlString: String, successBlock :@escaping (_ response :AnyObject)->Void, errorMsg:@escaping (_ errorMessage :String)->Void )
{
var request = URLRequest(url: URL(string: urlString)!)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { (data, urlResponse, error) in
DispatchQueue.main.async {
if(error == nil)
{
do {
// Here is the warning
let responseJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? AnyObject
guard let _ = responseJSON else {
errorMsg("Some error has been occurred!")
return
}
successBlock(responseJSON!)
}
catch
{
errorMsg("Some error has been occurred!")
}
}
else
{
errorMsg(error!.localizedDescription)
}
}
}
task.resume()
}
}
如果您正在阅读本文,谢谢您的时间!
答案 0 :(得分:4)
此功能
let responseJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? AnyObject
返回Any
,然后将其强制转换为AnyObject
,这几乎是相同的,最好将其强制转换为预期的json内容,无论是数组还是字典
let responseJSON = try JSONSerialization.jsonObject(with: data!) as? [String:Any]
或
let responseJSON = try JSONSerialization.jsonObject(with: data!) as? [Any]
并相应地更改完成