Capturing values in Closure

Updated 28 March 2023

Save

Today, we are going to learn about capturing value in the closure.

Firstly, we need to know What is closure?

According to Swift docs: Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures can store references and capture to any constants and variables from the context in which they are defined. 

Capturing Values in Closure

Closure can store references and capture values to any variables and constant from the context in which they are define, For example, class.

Swift can handle all of the memory management of capturing variables and constants.

For example:

We have created an empty closure for every iteration of the loop and added it to an array “closureArr”

closure body contains only a single expression that prints the value of “i” .

Above closure captures the “i” current address and it returns the current value, every time we access “i”

Points related to capturing value:

Capture list:

Swift uses capture lists to break strong reference cycles.

If we want to prevent capturing values behavior and print the value  i even if the properties change after they’re captured inside the closure.

We can explicitly capture the variable with a capture list like this:

In this way, we keep an immutable copy of j". Thanks to this copy, further changes j", outside the closure, will not affect the closure. j" is a let constant here. It is not mutable.

In conclusion, we have learned about capturing values in closures.

Lastly, please share your thoughts and queries below.

For more blogs please click here

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home