1 minute read

How ARC actually works in Swift

I'm a teenager in Atyrau, Kazakhstan, and I ship small iOS apps in Swift with UIKit, sometimes SwiftUI, testing them on a phone rather than a desk. Writing from a city of 300,000 people makes Apple's memory behaviour strangely personal: every gigabyte on the device is shared with system processes, and the moment something owns too much, the app disappears without explanation. Australian readers meet the same pressure from the other side of the planet, where iPhones are handed down between family members and a heatwave in Adelaide or Melbourne makes a handset work harder before lunch.

This piece is about the machinery under the hood: how reference counting decides when a Swift object dies, why one strong reference can keep an entire screen alive forever, and how to find the leak before your users do. I learned most of it while building an app for the WWDC Swift Student Challenge, where judges in Cupertino would run your code on their own hardware. ARC is easy to ignore until a scroll view stutters, a battery drains overnight, or the system kills your app while it sits in the dock.

What ARC actually counts

Automatic Reference Counting is not a runtime garbage collector that pauses your app to hunt for garbage. The compiler inserts retain and release calls around every reference it can prove, and the runtime keeps one counter per object: how many strong references point at it. When that count reaches zero, the object's deinit runs and its memory goes back. Ownership is explicit and cheap, so there is no surprise pause on a tram through Melbourne or a train from Parramatta into the Sydney CBD.

Two categories sit on either side of that counter. Value types — structs, enums, tuples — are copied when you assign or pass them, and their storage travels inline. Reference types — classes — are shared. Copying a struct that holds a photo gives you a new copy; copying a class gives you a second name for the same object, and the second name keeps the object alive. That is why handing a fresh UIViewController to a property leaves the previous instance in memory until the replacement takes over.

The counter counts edges, not values, and only strong ones count. Australia, with roughly 27 million people, consistently ranks among the world's biggest paid-app markets, so an app of yours can end up a real tool for someone rather than a weekend experiment. The arithmetic underneath does not change: every strong edge you add is a vote for staying alive, and every one you remove is a vote for going away.

Strong, weak and unowned relationships

Every reference has a strength, and the strength decides whether it votes. strong is the default: it keeps the target alive, and it keeps you alive too. weak registers an interest without voting, and silently becomes nil when the target dies, which is why it must be an optional. unowned also does not vote, but it does not become nil; it trusts that the target will outlive it and traps with a crash if that trust is broken. unowned(unsafe) skips even that check on performance-critical paths.

The mental model I use is a story passed around a room. The story lives as long as somebody is holding it, and it is a bit like dinner-time conversations in a shared house: the evening exists only while people are still talking about the day. A strong reference is someone actively holding the story. A weak reference is somebody who remembers it but will happily let it go. An unowned reference is a speaker who assumes the audience will still be there when they finish.

The distinction matters whenever two objects point at each other. A parent view controller holding its child strongly, with the child holding its parent strongly, means neither count reaches zero, so neither deinit ever runs and the whole hierarchy leaks. A weak reference expresses the weaker relationship: I know this object, I do not own it. It is the standard choice for delegates, for a child view's back reference, and for a closure that should not drag its owner along.

Australian rules add a reason to hold memory carefully. Under the Privacy Act 1988 and the Australian Privacy Principles, personal details kept about Australian users have to stay protected and accurate, and the Australian Consumer Law expects clear disclosure when an app asks for location, camera, or health access. A cached photo or cached address sitting inside a long-lived object is both a memory problem and a data-handling problem you would eventually have to explain.

A field guide to reference strengths

Here are the relationships I reach for most often, and the symptoms that tell me I chose wrong.

Relationships that usually want a weak or unowned reference

  • A view controller's delegate declared weak, so the controller can be released once the window drops it.
  • [weak self] inside an escaping closure that the same object stores, breaking the cycle at the capture site.
  • unowned self where the surrounding code guarantees the lifetime, such as a child its parent will certainly destroy first.
  • Weak caches for expensive objects, like a decoded image or a parsed API response, so the cache does not pin memory forever.

Signs that something is retaining too much

  • deinit never prints, even though the screen was dismissed.
  • The memory graph shows a chain of objects all pointing back to the same root.
  • Instruments reports leaked bytes after a short session.
  • Memory grows every time you reopen the same list cell.

Retain cycles hiding in closures and timers

Closures are where most cycles are born. A closure captures the variables it mentions, and by default that capture is strong. If an escaping closure is then stored on the object it captured, the object holds the closure and the closure holds the object, and the two keep each other warm indefinitely. The fix is to state ownership at the capture site with [weak self] or [unowned self].

Timers and observers are the usual accomplices. Timer.scheduledTimer retains its block, and a block that mentions self retains that self, so a repeating timer on a view controller keeps the controller and its views alive for as long as the timer fires. The same pattern appears with CADisplayLink, DispatchWorkItem, NotificationCenter block observers, and Combine subscriptions stored in properties. Invalidate them in deinit or viewDidDisappear, and capture weakly so the cleanup code can still run.

Context sharpens this in Australia. Apps here tend to sit in the background for a long time: an AFL match on a Tuesday night, a train from Canberra toward Wagga Wagga, a beach day at Bondi in January. Each is a chance to keep a dozen screens alive while the device also runs Maps, Music, and a family group chat. Summer heat in Adelaide pushes the thermals hard, so jetsam kills the process under the least memory pressure, and a leak that survived a mild European winter becomes a crash during a January school holiday in Queensland.

Tracing ownership in Xcode and Instruments

Xcode gives you more than a number in a gauge. The Memory Graph debugger can walk every strong reference in your app: select an allocation, open the debug navigator's memory graph, and the reference counts panel lists what points at the object and what it points at. Option-clicking a node reveals the incoming and outgoing edges, which is how you find the offending arrow in a cycle instead of guessing.

Instruments adds the timeline. The Allocations template separates persistent bytes, memory that never came back, from transient bytes, and marks leaks it believes are lost for good. The Leaks template runs at the end of a session and reports objects with no surviving references, including ones still alive but unreachable from any root. I run a short leak check after each feature rather than before a release, because a five-minute session catches the obvious cycles and stays short enough that I actually repeat it.

There is also a cheap trick that catches more than you would expect: put a print statement in deinit. When a screen's deinit fires right after you dismiss it, ownership is behaving. When it never fires, something in the chain still holds a strong reference, and your search narrows to that chain rather than the whole app.

The habit worth keeping

ARC gives you deterministic ownership, not automatic correctness. The compiler manages the counter; it cannot infer whether a relationship should be strong. Remember that a class instance lives exactly as long as its strong references allow, that weak is the honest way to say I know this object but I do not own it, and that unowned is a promise you have to be able to keep.

When memory climbs, when deinit stays silent, or when the system kills your app on a hot afternoon in Melbourne, follow the references instead of the symptoms: find the chain, find the unexpected strong edge, and change that one relationship to a weak or unowned one. Ownership in Swift is a small explicit contract, and once you read your code as a graph of strong references rather than a list of variables, the leaks stop being mysterious and start being obvious.

Updated: