【发布时间】:2020-05-04 04:48:39
【问题描述】:
我的 swift 有问题。我正在尝试发送 API 请求然后检索数据,但收到以下错误消息:
“Swift:转义闭包捕获非转义参数'onCompletion'”。
有谁知道我该如何解决这个问题?提前致谢
代码:
class RestApiManager: NSObject {
static let sharedInstance = RestApiManager()
let baseURL = "http://api.randomuser.me/"
func getRandomUser(onCompletion : (JSON) -> Void) {
makeHTTPGetRequest(path: baseURL, onCompletion: { json, err -> Void in
onCompletion(json)
})
}
func makeHTTPGetRequest(path: String, onCompletion: ServiceResponse) {
let request = NSMutableURLRequest(url : URL(string: path)! as URL)
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
let json:JSON = JSON(data as Any)
onCompletion(json, error as NSError?)
})
task.resume()
}
}
【问题讨论】:
-
检查这个:stackoverflow.com/a/46245943/5492956;
Escaping Closure: An escaping closure is a closure that’s called after the function it was passed to returns. In other words, it outlives the function it was passed to. Non-escaping closure: A closure that’s called within the function it was passed into, i.e. before it returns.