Capture list In Swift

Shantaram Kokate
2 min readNov 27, 2020

--

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 inkeywords, 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 variableaand b are Int Type i.e Value Type in swift

In the above code, ais included in the capture list, but bnot.

capture variableais 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 ado 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

If you like this post, please share and give claps so others can find it 👏👏

You can follow me on Medium for updated articles. Also, connect with me on LinkedIn, Twitter.

If you have any comments, questions, or recommendations, feel free to post them in the comment section below!👇

--

--