Swift 3:关闭使用非转义参数可能允许它逃脱 [英] Swift 3 :Closure use of non-escaping parameter may allow it to escape

查看:566
本文介绍了Swift 3:关闭使用非转义参数可能允许它逃脱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下功能,我有完成处理程序,但我收到此错误:

 关闭使用非转义参数可以允许它逃避

这是我的代码:

  func makeRequestcompletion(完成:(_ 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
完成(数据,错误)//< - 这里是我收到错误
})
task.resume()
}
}


你们中的任何人都知道我为什么会收到此错误?



我真的很感谢你的帮助


解决方案

看起来你需要明确定义允许关闭转义。



来自 Apple Developer docs


当闭包作为参数传递给函数时,闭包被称为转义函数,但在函数返回后调用。当您声明一个以闭包作为其参数之一的函数时,您可以在参数的类型之前编写@escaping以指示允许闭包转义。


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

  func makeRequestcompletion(完成:@escaping(_ response:Data,_ error:NSError) - > Void){
let urlString = URL(string:http://someUrl.com)
if let url = urlString {
让task = URLSession.shared.dataTask(带:url,completionHandler:{(数据,urlRequestResponse,错误)
完成(数据,错误)//< - 这是我'得到错误
})
task.resume()
}
}


I have the following function where I have completion handler but I'm getting this error:

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

Here is my code:

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

Any of you knows why I'm getting this error?

I'll really appreciate you help

解决方案

Looks like you need to explicitly define that the closure is allowed to escape.

From the 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; Add the @escaping keyword after the completion variable:

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

这篇关于Swift 3:关闭使用非转义参数可能允许它逃脱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆