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

后端 未结 3 719
梦如初夏
梦如初夏 2020-12-15 22:05

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
         


        
3条回答
  •  旧时难觅i
    2020-12-15 22:20

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

提交回复
热议问题