skip to content

As lead of a Swift app team, how would you catch retain cycles before a release ships, and where would you still allow `unowned`?

level: principalimportance: should knowfreq 35%

answer

  1. no compiler error for a cycle
  2. ownership rules in review
  3. deinit-based tests per flow
  4. reachable is not leaked
  5. unowned needs a written lifetime

basics

~20 s

Layer the defences: an ownership rule enforced in review, deinit-based leak tests for each screen flow, the compiler's capture warnings made errors, and a memory-graph pass on key flows before release. Allow unowned only where the owner provably outlives the holder.

solid answer

~50 s

Nothing in Swift rejects a retain cycle at compile time, and leak tools only see cycles nothing can reach, so no single check is enough. I would set an **ownership convention** (owners strong; delegates and back-references `weak` and class-bound; every timer, observer and stored closure has an explicit stop), add **automated deinit tests** that drive a flow and assert the screen and view model are freed, promote the compiler's `ImplicitStrongCapture` warning to an error, and run **Xcode's memory graph debugger** over the main flows before each release. `unowned` stays allowed where the referenced object owns the holder and the reference never escapes, with the lifetime written in the review; `unowned(unsafe)` needs a profile showing the check matters. The trade-off is test and review cost against leaks that otherwise surface as memory growth reported from the field.

code

swift · 26 lines
swift
protocol ProfileViewModelDelegate: AnyObject { func profileDidLoad(name: String) }

final class ProfileViewModel {
    var delegate: ProfileViewModelDelegate?        // bug under test: strong back-reference
    func load() { delegate?.profileDidLoad(name: "Ada") }
}

final class ProfileScreen: ProfileViewModelDelegate {
    let viewModel = ProfileViewModel()
    init() { viewModel.delegate = self }
    func profileDidLoad(name: String) {}
}

/// Drives one flow, then reports whether the object was freed.
func deallocates<T: AnyObject>(_ make: () -> T, drive: (T) -> Void) -> Bool {
    weak var probe: T?
    do {
        let object = make()
        probe = object
        drive(object)
    }                       // the only strong reference ends here
    return probe == nil
}

let freed = deallocates({ ProfileScreen() }, drive: { $0.viewModel.load() })
print(freed ? "freed" : "LEAK: ProfileScreen still alive")   // prints the LEAK line

go deeper

for a junior

Know that Swift does not reject a retain cycle at compile time and that a deinit print is the simplest way to see whether a screen was freed.

for a middle

Explain how a weak probe test works and why leak tools only report objects nothing reachable points to.

for a senior

Diagnose with the memory graph debugger and malloc stack logging, and know which cycles each tool and test can and cannot see.

for a principal

Own the layered policy: which rules reviewers enforce, which checks gate CI, who runs the release pass, and when unowned is allowed with a written lifetime.

## Why cycles reach production A **retain cycle** (a strong reference cycle) in Swift compiles cleanly: each stored property or capture is legal on its own, and ARC simply never frees the objects involved. Two more facts make cycles slip through: - **Leak tools see only unreachable memory.** Instruments' Leaks and the `leaks` command-line tool report allocations nothing reachable points to. An object kept alive through a run loop's timer, a singleton or a notification registration is still reachable, so it never shows up as a leak. - **Symptoms are indirect.** A leaked screen keeps its observers, timers and network callbacks alive; users see duplicated work, stale UI updates or memory growth, long after the code review. So a lead needs several cheap layers rather than one heroic tool. ## Layer 1: an ownership convention in review Write down the rules reviewers apply: - Owners hold strongly: a screen owns its view model, a view model owns its services. - Back-references are `weak`, with class-bound (`AnyObject`) delegate protocols. - Closures stored on an object, and timers, observers and subscription tokens, are cleared by an explicit `stop()` or `cancel()` tied to a lifecycle event, not only in `deinit`, because a `deinit` cannot run while a cycle holds its own object. - The rule for capture lists in escaping closures is set with the Swift material on closures; this policy only has to be consistent with it. ## Layer 2: the compiler Swift 6.4 warns when an inner closure captures `[weak self]` while an outer escaping closure has already captured `self` strongly: "'weak' ownership of capture 'self' differs from implicitly-captured strong reference in outer scope", in the `ImplicitStrongCapture` diagnostic group. Since Swift 6.1, `-Werror ImplicitStrongCapture` turns just that group into an error, so CI fails on it. If the team adopts Swift 6.2's opt-in strict memory safety mode, every use of an `unowned(unsafe)` reference is flagged as an unsafe construct, which keeps that escape hatch visible. ## Layer 3: automated leak tests The cheapest reliable test drives one flow, drops the last strong reference and checks a `weak` probe: 1. Create the screen and keep a `weak` reference to it. 2. Drive the flow: load, tap, dismiss. 3. Let the local strong reference end, then assert the weak probe is `nil`. Cover every screen that is pushed or presented, plus anything that starts a timer, registers an observer or stores a closure, because those are where cycles hide. The test framework's teardown hooks make this a one-line helper per test case; the details belong with the testing tools. For command-line targets on macOS, `leaks --atExit -- <binary>` reports unreachable cycles by class name and exits non-zero when it finds leaks, which a CI step can gate on. ## Layer 4: a release check with the memory graph debugger Before a release, walk the main flows in a debug build, return to the start, and open Xcode's memory graph: any screen or view model still listed is suspect, and the graph shows the reference path keeping it alive. Turning on malloc stack logging in the scheme adds the allocation backtrace for each object. ## Where unowned is still allowed | Reference | Policy | Failure mode | |---|---|---| | `weak` | default for every back-reference | silent `nil`; a skipped call | | `unowned` | allowed when the referenced object owns the holder and the holder never escapes to longer-lived code; lifetime written in review | a run-time trap on the first stale read | | `unowned(unsafe)` | only with a profile showing the check matters and a proven lifetime | reads freed memory; no trap | Banning `unowned` is simpler to enforce, but the trap is a feature: it exposes a broken lifetime assumption at the read that breaks it, where `weak` would hide it behind an optional. ## Trade-offs to own 1. Leak tests cost upkeep and only cover the flows they drive. 2. Review rules depend on reviewers; the compiler's warning covers only the nested-capture case. 3. The memory-graph pass is manual, so it belongs on the release checklist with a named owner. 4. Field memory metrics remain the backstop for leaks none of the layers predicted.

  • Why not ban `unowned` outright?
    A ban is easy to enforce and removes a crash class, but it costs clarity where the lifetime really is tied, such as a child its owner creates and never hands out. There `weak` adds optional unwrapping and a silent `nil` path that hides a broken assumption the trap would expose. Allowing `unowned` with the lifetime written in review is the usual middle ground.
  • What does a deinit-based leak test miss?
    It proves only that the objects it probes are freed along the path it drives. A leaked helper the test does not probe, such as an observer or a timer target created inside the flow, passes unnoticed, and flows the test never triggers are invisible. That is why the release memory-graph pass and field memory metrics stay in the plan.
  • How do you make the nested-capture warning block a merge without failing on every warning?
    Promote just its diagnostic group. Since Swift 6.1 the compiler accepts `-Werror ImplicitStrongCapture`, so a `[weak self]` that an outer escaping closure has already undermined with a strong capture fails the build, while unrelated warnings stay warnings.

  • The Swift compiler refuses to build a retain cycle, so review can skip ownership.
  • Instruments' Leaks finds every object that should have been freed.
  • Replacing every unowned with weak removes the app's memory leaks.
  • Mandating [weak self] everywhere makes leak tests unnecessary.
  • unowned(unsafe) is a free speed-up that needs no review.

Assumes the Swift 6.4 compiler; per-group -Werror arrived in Swift 6.1 (SE-0443) and opt-in strict memory safety in Swift 6.2 (SE-0458).