Most common memory leak trap in Swift

Powersurge⚡️
2 min readJan 4, 2017

--

Have you ever called a method that takes a closure in Swift? Something that looks like this:

If you write any code in that closure that refers to self.it is a potential memory leak.

You can easily test your memory leaks with the “Debug memory graph” in xCode by pressing that weird button that looks like this:

If you have memory cycles it will show you warnings like that in the debugger:

If you do have one (or usually bunch) it is showing you that you have an object that has been leaked.

How do you prevent that?

It is as simple as adding [unowned self]into the first line of your closure!

THAT’S IT! It will stop the leak.

The reason why the memory leak is happening is because closures in Swift have to capture the scope (i.e. everything that between those {} brakets) and if you refer to anything self. it has to retain a strong pointer to that object and it is never gets released even the whole viewController may have been deallocated.

[unowned self]is your friend in Swift closures!

UPDATE: As Medium readers pointed out, it is also possible instead of [unowned self] to use [weak self] which will also stop the leak. However there are some important considerations pointed out by Tudor Andrei Marinescu:

The difference between unowned and weak is that weak is declared as an Optional while unowned is not. By declaring it weak you get to handle the case that it might be nil inside the closure at some point. If you try to access an unowned variable that happens to be nil, it will crash the whole program. So only use unowned when you are positive that variable will always be around while the closure is around

--

--