Swift Review — Closures(2)
Source: https://docs.swift.org/swift-book/LanguageGuide/Closures.html
- Capturing Values
We have discussed how Swift distinguishes closures(function, nested function, and closure expression). In effect, they are different in that nested functions and closure expressions CAPTURE constants and variables from the surrounding contexts.
What exactly does it mean by CAPTURING values? Swift basically treats closures as reference types, so that it stores those values in the memory heap of the device and calls them by reference(but about this point, Swift Docs also says it merely stores a copy rather than the value itself if it is not mutated in the future, for the sake of optimization). This is why we generate a strong reference cycle when we assign a closure to a property of a class instance, and that closure captures values defined within that class or the class instance itself.
2. Escaping Closure
You’ll see the property wrapper @escaping in front of closures as arguments of functions. What it means is that these closures are NOT called until the functions return. They are called AFTER the functions return. For example, a function needs a completion handler after it finishes what it intends to do. However, the completion handler must not be called before that intention is fulfilled.
One thing that is not clear about this escaping closure is that why escaping closures must explicitly refer to a class instance self whereas nonescaping ones need not. The Swift Docs merely says it is required to avoid a strong reference cycle. However, probably due to the new updates in Xcode, there occurs no strong reference cycle error in the example the Swift Docs provides. Hence, it seems now only to avoid the ambiguity of reference when it comes to an escaping closure since it is called after the function return so that it is not clear which value the closure refers to.
Basically, escaping closures are used when we want to treat them as parameters and refer to them, rather than as closures doing their job within the functions surrounding them.