从'NSData'转换为不相关的类型'NSHTTPURLResponse'总是失败

时间:2016-03-14 18:58:53

标签: swift casting nsdata httpresponse nshttpurlresponse

我有这段代码:

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

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

1 个答案:

答案 0 :(得分:1)

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

另外,为什么要强行展开垂头丧气?

最好像你已经那样继续使用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()