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

user2924482 picture user2924482 · Feb 13, 2017 · Viewed 14.1k times · Source

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

enter image description here Any of you knows why I'm getting this error?

I'll really appreciate you help

Answer

Mark Barrasso picture Mark Barrasso · Feb 13, 2017

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