从 'NSData' 转换为无关类型 'NSHTTPURLResponse' 总是失败

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

我有这个代码:

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

在线:let httpResponse = response as! NSHTTPURLResponse 我有这个奇怪的警告:Cast from 'NSData' to unrelated type 'NSHTTPURLResponse' always fails

我应该如何摆脱它?谢谢!

您正在将 data 的内容解包到名为 response 的常量中。这是你问题的根源,因为你正在使用一个以为你正在使用另一个。

还有,为什么要强制展开 downcast?

最好继续像您一样使用 guard

示例:

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