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