Capture list In Swift
What is a capture list?
The capture list is described as a “comma-separated list enclosed in square brackets” before the list of parameters. When using a capture list, always use in
keywords, even if you omit the parameter name, parameter, and return types.
var closure = { [variable1, variable2, variable3, ...] in }
capture list creates a local variable in the closure. It is initialized with the value of the variable with the same name in the outer context.
let understand the capture list using value type and reference type.
1. capture list with value type
let start with outer variablea
and b
are Int Type i.e Value Type in swift
In the above code, a
is included in the capture list, but b
not.
capture variablea
is initialized with an outer variable a
when the closure is created but those variables are not pointing to the same memory location. because Int is a value type. That is, changes in the outer variable a
do not affect the capture of the local variable a
, and changes inside the closure do not affect anything outer variable a
.
Note: To create a capture list make sure that outer variable and capture variable name should be same
In contrast, there is only one variable named b
, so that change affects both inside and outside variable. because we have not captured this variable inside closure.
2. capture list with reference type
Why we use capture list?
Capture List used to break a Retain Cycle