Search code examples
swiftcastingnsdatahttpresponsenshttpurlresponse

Cast from 'NSData' to unrelated type 'NSHTTPURLResponse' always fails


I have this code :

let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in

            guard let response = data else {
                print("Error: did not receive data")
                return
            }

            guard error == nil else {
                print("error")
                print(error)
                return
            }

            let httpResponse = response as! NSHTTPURLResponse
            let statusCode = httpResponse.statusCode

            if (statusCode == 200) {
                print("OK!!!")
            }
        })

        task.resume()

At the line : let httpResponse = response as! NSHTTPURLResponse I have this strange warning : Cast from 'NSData' to unrelated type 'NSHTTPURLResponse' always fails

How should I get rid of it ? Thanks!


Solution

  • You are unwrapping the content of data in a constant called response. It's the source of your issue, because then you are using one thinking you are using the other.

    Also, why force unwrapping the downcast?

    It's better to continue using guard like you already do.

    Example:

    let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
    
        guard let data = data else {
            print("Error: did not receive data")
            return
        }
    
        guard error == nil else {
            print("error")
            print(error)
            return
        }
    
        guard let httpResponse = response as? NSHTTPURLResponse else {
            print("response unavailable")
            return
        }
    
        let statusCode = httpResponse.statusCode
    
        if statusCode == 200 {
            print("OK!!!")
        }
    })
    
    task.resume()