Search code examples
iosswiftnsurlsessionnsjsonserialization

How to remove warning "Conditional cast from 'Any' to 'AnyObject' always succeeds"


I create a class and I'm getting an warning message when I try to cast an object as AnyObject. The warning is: " Conditional cast from 'Any' to 'AnyObject' always succeeds " How can I remove this warning from my file ?

Here is my code:

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()
    }
}

Thank you guys for your time if you are reading this !


Solution

  • This function

    let responseJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? AnyObject 
    

    returns Any and you cast it to AnyObject which nearly the same , it's better to cast to the expected json content whether it's an array or dictionary

    let responseJSON = try JSONSerialization.jsonObject(with: data!) as? [String:Any] 
    

    Or

    let responseJSON = try JSONSerialization.jsonObject(with: data!) as? [Any] 
    

    and change the completion accordingly