为什么Swift中的这个Apple示例不适合我?

时间:2016-11-24 15:52:05

标签: ios swift swift3 nsurlsession

我关注this Swift Post(Apple于2016年9月发布)。

该帖子实现了以下扩展,如下所示:

extension Restaurant {
    private let urlComponents: URLComponents // base URL components of the web service
    private let session: URLSession // shared session for interacting with the web service

    static func restaurants(matching query: String, completion: ([Restaurant]) -> Void) {
        var searchURLComponents = urlComponents
        searchURLComponents.path = "/search"
        searchURLComponents.queryItems = [URLQueryItem(name: "q", value: query)]
        let searchURL = searchURLComponents.url!

        session.dataTask(url: searchURL, completion: { (_, _, data, _)
            var restaurants: [Restaurant] = []

            if let data = data,
                let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                for case let result in json["results"] {
                    if let restaurant = Restaurant(json: result) {
                        restaurants.append(restaurant)
                    }
                }
            }

            completion(restaurants)
        }).resume()
    }
}

当我尝试在我自己的项目中重新创建它时,我收到以下消息:

  

无法使用类型'的参数列表调用'dataTask'(with:String,   completionHandler :() - > ())'

为什么帖子与XCode 8.1告诉我的内容之间存在差异?他们都在同一时间被释放。

我正在使用Swift 3.0

1 个答案:

答案 0 :(得分:0)

您错过了in关键字,应该是。

修改 正如@leo所指出的,你的论据列表也是错误的,改为:
(_, _, data, _)(data, response, error)

所以它应该是这样的:

session.dataTask(url: searchURL, completion: { (data, response, error) in

请注意该行末尾的in。这是closures taking arguments的语法。