我正在关注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/