gpt4 book ai didi

ios - swift 3 :Closure use of non-escaping parameter may allow it to escape

转载 作者:IT王子 更新时间:2023-10-29 05:41:49 25 4
gpt4 key购买 nike

我有以下函数,其中有完成处理程序,但出现此错误:

Closure use of non-escaping parameter may allow it to escape

这是我的代码:

func makeRequestcompletion(completion:(_ response:Data, _ error:NSError)->Void)  {
let urlString = URL(string: "http://someUrl.com")
if let url = urlString {
let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, urlRequestResponse, error) in
completion(data, error) // <-- here is I'm getting the error
})
task.resume()
}
}

enter image description here你们中有人知道我为什么会收到此错误吗?

非常感谢你的帮助

最佳答案

看起来您需要明确定义允许闭包转义。

来自Apple Developer docs ,

A closure is said to escape a function when the closure is passed as an argument to the function, but is called after the function returns. When you declare a function that takes a closure as one of its parameters, you can write @escaping before the parameter’s type to indicate that the closure is allowed to escape.

TLDR;在完成变量后添加@escaping关键字:

func makeRequestcompletion(completion: @escaping (_ response:Data, _ error:NSError)->Void)  {
let urlString = URL(string: "http://someUrl.com")
if let url = urlString {
let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, urlRequestResponse, error) in
completion(data, error) // <-- here is I'm getting the error
})
task.resume()
}
}

关于ios - swift 3 :Closure use of non-escaping parameter may allow it to escape,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42214840/

25 4 0