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.

--

--