Looking for swift Answers? Try Ask4KnowledgeBase
Looking for swift Keywords? Try Ask4Keywords

Swift Language Reference Cycles and Weak References


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.