Preventing the Retain Cycle Memory Leak Of Strong Swift Arrays

Let’s create a retain cycle memory leak with arrays:

Click For Gist

Subscriber holds publisher strong and publisher holds its subscribers back in its subscribers array. Paste the code into your playground and observe that deinit never gets called, too bad!

Click For Gist

The array itself can not be a weak reference. But its elements can be defined as weak references in some way. To achieve this, we need to use a generic wrapper around strong elements to weakify them as shown above.

--

--

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