我有这段代码:
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
我应该如何摆脱它?谢谢!
答案 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()