Swift Language Memory Management Reference Cycles and Weak References

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

A reference cycle (or retain cycle) is so named because it indicates a cycle in the object graph:

retain cycle

Each arrow indicates one object retaining another (a strong reference). Unless the cycle is broken, the memory for these objects will never be freed.

A retain cycle is created when two instances of classes reference each other:

class A { var b: B? = nil }
class B { var a: A? = nil }

let a = A()
let b = B()

a.b = b  // a retains b
b.a = a  // b retains a -- a reference cycle

Both instances they will live on until the program terminates. This is a retain cycle.

Weak References

To avoid retain cycles, use the keyword weak or unowned when creating references to break retain cycles.

class B { weak var a: A? = nil }

Weak or unowned references will not increase the reference count of an instance. These references don't contribute to retain cycles. The weak reference becomes nil when the object it references is deallocated.

a.b = b  // a retains b
b.a = a  // b holds a weak reference to a -- not a reference cycle

When working with closures, you can also use weak and unowned in capture lists.



Got any Swift Language Question?