Closure Retain Cycle in Swift

Kaan Vural
2 min readMay 17, 2020

Before you begin I highly recommend you to check ARC story.

We will begin with checking no memory leak case in closures;

Prints Initialized and Deinitialized

The closure block is separate from the Human object and the humanClosure property has a reference to the closure block.

Since the Human object as one reference from the kaan property, we able to deallocate.

The closure block has been also deallocated due to the reference count of zero.

Now, check below case.

Prints only Initialized with Kaan

Let us visualize the relationship to see the retain cycle.

Even if you assign kaan object to nil value, above 2 relation will be exist on memory.

To overcome the result above, we must use capture lists. You will capture self as a weak reference.

Prints Initialized with Kaan and Deinitialized
Will be removed completely.

Be careful when you use self keyword in closure. (indicates there may be a retain cycle)

However, the capture self within the closure has turned into an optional type. Let us review the rule of weak.

  • A weak reference allows the referencing object to becoming nil (this happens automatically when the referenced object is deallocated)
  • Based on the rule above, the referencing object/variable must be optional

--

--