O'Reilly logo

Swift Functional Programming - Second Edition by Dr. Fatih Nayebi

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Capturing values

Closures can capture variables and constants from the surrounding context in which they are created. Closures can refer to these variables and modify them within their body, even if the original scope that defined variables no longer exists.

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. One way that a closure can escape is by being stored in a variable that is defined outside the function.

The following is an example of escaping closures, in other words, completion handlers:

func sendRequest(completion: @escaping (_ response: String?, _ error: Error?) -> Void) {     // execute some time consuming operation, if successfull {  completion("Response", ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required