1

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!

sschale
  • 5,168
  • 3
  • 29
  • 36
Dani Turc
  • 39
  • 2
  • 11

1 Answers1

1

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()
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
  • Thanks this kinda fix it, but it gives me another warning on line : guard let data = data else { ; the warning is : Immutable value 'data' was never used; consider replacing with '_' or removing it ... PS: Sorry a novice!!! – Dani Turc Mar 14 '16 at 20:25
  • The compiler is just telling you that you unwrap `data` but you don't use it - which is true. You can silence the warning by replacing `guard let data = data` with `guard let _ = data` if you don't use `data` at all in this task. – Eric Aya Mar 14 '16 at 20:28
  • Thanks alot for the help and explanation! – Dani Turc Mar 14 '16 at 20:29