Reference cycles in closures

Shinto Joseph
1 min readJun 6, 2021

--

Reference cycles happens in closures because they are basically reference types

The name closure comes from enclosing

In Swift closure captures variables and constants from surrounding scope

The strong reference cycle of closure

Eg

This can be solved by capture lists

Swift wants you to use self keyword in closures as a reminder that a reference to the current object is being captured

Capture list

Array of variable that are captured by closure

We will use in key work to separate the variables in square bracket and rest of the closure body

For a closure with both parameter list and capture list the capture list comes first

By capture list swift means that the current value of the variable is captured and stored in a local variable in the capture list array

Since the prityprint() function will not exist if we release Person from memory we can make it unowned

Weak self

Some times you cant capture self as unowned reference, It can become nil sometime when running asynchronous task

consider prityprint is happening in a asynchronous task

A weak self reference will extends objects life cycle for asynchronous calls

--

--