URLSession在Swift 3中引发转换错误

时间:2016-10-11 10:03:44

标签: swift xcode swift3 nsurlsession

我刚刚下载了Xcode8,现在是以前的功能代码:

let Task = URLSession.sharedSession.dataTaskWithRequest(Request) {

   (data : NSData!, response : URLResponse!, error : NSError!) in

}

抛出错误:

Cannot convert value of type '(NSData!, URLResponse!, NSError!) -> ()' to expected argument type '(Data?, URLResponse?, Error?) -> Void'

Xcode 2有什么问题或有变化?

2 个答案:

答案 0 :(得分:0)

如果你给他们选择('?')而不是强迫他们,他们似乎没有任何问题:

let task = URLSession.shared.dataTask(with: Request) {

    (data : Data?, response : URLResponse?, error : Error?) in

}

答案 1 :(得分:0)

错误消息只是说编译器需要

let task = URLSession.sharedSession.dataTaskWithRequest(request) {

   (data : Data?, response : URLResponse?, error : Error?) in

}

但你根本不需要类型注释,它可以神奇地避免错误

let task = URLSession.sharedSession.dataTaskWithRequest(request) {

   (data, response, error) in

}

但是在Swift 3中你必须写

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in ... }