【问题标题】:Why is this Apple example in Swift not working for me?为什么 Swift 中的这个 Apple 示例对我不起作用?
【发布时间】:2016-11-25 00:04:21
【问题描述】:

我关注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()
    }
}

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

不能使用类型为 '(with: String, 完成处理程序:() -> ())'

为什么这篇文章和 XCode 8.1 告诉我的有出入?他们都在同一时间发布。

我使用的是 Swift 3.0

【问题讨论】:

  • 这与 Swift3 不兼容(扩展中的属性,++)。

标签: ios swift swift3 nsurlsession


【解决方案1】:

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

编辑: 正如@leo 所说,您的参数列表也是错误的,请从:
(_, _, data, _) 更改为(data, response, error)

所以它应该是这样的:

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

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

【讨论】:

  • @LeoDabus 不错!不是说那也可能是错的,只是看到了丢失的“in”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-10
  • 1970-01-01
  • 1970-01-01
  • 2018-06-12
  • 2014-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多