Memory leak caused by closure

Circular reference

In Swift, Closure is something very popular which We may have to use on a daily basis, however sometimes careless in using.

swift closure.png

There is a potential risk in using closure, that is memory leak. Memory leak is the case in which you have given up access to the object which is not able to be deinited due to circular strong references it gets involved.

In case of objects relationship, A refers to B, and B refers back to A. We’re easily to find out a strong circular reference and easy to break it down by turning one of references to weak/unowned reference. This is the case We usually know


In the post, I bring up the second case which We usually pay less attention. The circular reference caused by relationship between an object and a closure.

Give an example

Open the XCode, create a playground and try this sample

Circular reference with closure sample


In the above piece of code, at the line #19 to #21 the class Student has var summaryInfo which holds a closure to print out the summary info of student itself. The point is the closure refers back to the object to take what it needs.

Student -> closure -> Student.

Strong Closure circular reference

This obviously makes up a circular reference, and the references are strong. So the objects of student class will not stand a chance to be deallocated.


Console output 1

In the console, it doesn’t show an info about object deinit when student goes out of scope, because the object is retained. This is bad.


In the given sample, We see the pattern. In order to break down the strong relationship, We may define an either weak or unowned reference in closure

Break down strong reference

We still have a circular reference, but one reference is strong and the other one is weak. They don’t retain each other.

Weak Closure circular reference

So now re-run the code, we’ll see the student object gets deallocated when it goes out of scope.

Console output 2

This is what We want. Good luck.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s