ios - 为什么 Swift 中的 Apple 示例不适合我?

标签 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()
    }
}

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

Cannot invoke 'dataTask' with an argument list of type '(with: String, completionHandler: () -> ())'

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

我使用的是 Swift 3.0

最佳答案

您缺少 in 关键字,应该是。

编辑: 正如@leo 指出的,你的参数列表也是错误的,更改自: (_、_、数据、_)(数据、响应、错误)

所以这应该是这样的:

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

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

关于ios - 为什么 Swift 中的 Apple 示例不适合我?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40790460/

相关文章:

swift - 遍历 NSDictionary 中的字符串数组

ios - HKSampleQuery 不返回任何结果,即使有

ios - 苹果和 Stripe : Merchant id/apple pay certificate could not seen in xcode

ios - 'top-down' UITableView 中 UITableViewCell 中的多个按钮

ios - 在 map View 中更改注释 View 的 rightCalloutAccessoryView 按钮的图像

ios - 如何获得 SKShapeNode 的准确触摸位置?

ios - 制作垂直移动背景

ios - NSPredicate 格式问题

ios - 使用框架 API token 验证来自 iPhone 的请求

ios - UIAlertController 不是窗口层次结构