Closure Retain Cycle in Swift

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.

Software engineer @huawei , musician

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store