SWIFT / CHAPTER 13

Reference ownership and closure cycles

Advanced

Recognize when strong references prevent intended cleanup.

By the end of this chapter

  • Trace strong-reference relationships
  • Use weak for optional nonowning links
  • Choose capture policies deliberately

The idea

Automatic reference counting keeps a class instance alive while strong references to it remain. A cycle can prevent instances from being released even after outside owners disappear. For example, an owner may retain a callback that strongly captures the owner itself. Draw the ownership arrows to identify the cycle instead of assuming that leaving a local scope always destroys every reachable object.

A weak reference does not keep its target alive and becomes nil when the target is released, so it uses optional handling. A weak self capture can break an owner-callback cycle, but the callback must define what happens when the owner is gone. unowned expresses a stronger lifetime assumption and is unsafe if that assumption fails. Select the relationship from the real lifetime contract rather than applying weak mechanically to every reference.

Swift example
class Token {}
var strong:Token?=Token()
weak var observer=strong
print(observer != nil)
strong=nil
print(observer == nil)
Result
true
true

The weak observer does not retain the token, so removing its only strong owner releases it and clears the observer.

Try it yourself

Describe a view-model callback ownership cycle and replace one strong capture with a safe weak capture.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Why can owner.callback = { owner.refresh() } create a cycle when callback is stored strongly?