Capture lists
A capture list is an array of variables which are captured by a closure. You use the in keyword to separate the variables between square brackets from the rest of the closure’s body. If the closure has both a parameter list and a capture list, the capture list comes first.
Consider the following code snippet:
var counter = 0
var closure = { print(counter) } counter = 1
closure()
The closure prints the counter variable’s updated value, as expected, because the closure captured a reference to the counter variable.
If you want to show the original value instead, define a capture list for the closure like this:
counter = 0
closure = { [counter] in print(counter) } counter = 1
closure()
The closure will now copy the value of counter into a new local constant with the same name. As a result, the original value 0 is printed.
When dealing with objects, remember that “constant” has a different meaning for reference types. With reference types, a capture list will cause the closure to capture and store the current reference stored inside the captured variable.
Changes made to the object through this reference will still be visible outside of the closure.
Now that you understand how capture lists work, it’s time to see how you can use them to break reference cycles for closures.