skip to content

ARC and Memory Safety

Automatic Reference Counting frees objects deterministically, so breaking cycles is your job, and exclusivity and ownership rules keep memory safe. Interviewers ask about leaks first.

on this pageshow

explore

questions

21

In Swift, which references keep a class instance alive under ARC, and at what moment does its deinit run?

level: juniorimportance: must knowfreq 75%

answer

  1. only one kind of type is counted
  2. strong is the default for every binding
  3. a struct can still own an object
  4. the release that reaches zero

basics

~20 s

Every strong reference keeps a Swift class instance alive: variables, constants, stored properties (a struct's included), collection elements and closure captures. When the last one is released, ARC runs deinit synchronously at that point and then frees the memory.

solid answer

~50 s

ARC counts strong references to class instances only. Structs and enums are not counted themselves, but a class reference stored inside one is a strong reference like any other. By default every `var`, `let`, stored property, array or dictionary element and closure capture is strong; references declared `weak` or `unowned` don't keep the instance alive, and neither does a raw pointer or an `Unmanaged` value. The compiler inserts retains where references are copied and releases where they are overwritten or end. The release that drops the strong count to zero runs a plain `deinit` immediately and synchronously on the thread that performed it, before the instance's own stored properties are released — so when assigning `nil` drops the last strong reference, the deinit has finished before the next line runs. Swift offers no public API to read the count; observe lifetime with `deinit` logging instead.

code

swift · 22 lines
swift
final class TempFile {
    let name: String
    init(name: String) { self.name = name }
    deinit { print("deinit: \(name)") }
}

struct Upload {                  // the struct itself is not reference counted,
    var file: TempFile           // but this stored property is a strong reference
}

var upload: Upload? = nil
var queue: [TempFile] = []

do {
    let file = TempFile(name: "draft.tmp")   // strong reference 1: the local constant
    queue.append(file)                       // 2: the array element
    upload = Upload(file: file)              // 3: the struct's stored property
}                                            // the local constant is gone: 2 left
queue.removeAll()                            // 1 left
print("still alive")
upload = nil                                 // last strong reference: deinit runs here
print("after release")

go deeper

for a junior

Recall that every class reference is strong unless marked weak or unowned, and that deinit runs as soon as the last strong reference is released.

for a middle

Explain where strong references hide: struct properties, collection elements and closure captures, and why each struct copy retains the object again.

for a senior

Show you know deinit runs synchronously on the releasing thread and cascades into the object's properties, and what that means for work done in deinit.

for a principal

Frame ARC's deterministic release as something code may depend on for cleanup, while avoiding designs that rely on globals or exact scope ends.

## What ARC counts **Automatic Reference Counting (ARC)** is how Swift decides when a **class instance** can be freed. The Swift book is explicit about its scope: reference counting applies only to instances of classes. Structures and enumerations are **value types** — each variable holds its own copy, so there is nothing shared to count. That does not mean value types are irrelevant to object lifetime. A struct whose stored property has a class type holds a **reference** to that instance, and that reference counts. Copying the struct copies the reference, so every copy keeps the object alive. The struct is not counted; what it stores is. ## Which references are strong A **strong reference** is one that keeps the instance from being deallocated for as long as it exists. In Swift, strong is the default for every place a class reference can live: | Where the reference lives | Keeps the instance alive? | |---|---| | a local or global `let` or `var` | yes | | a stored property of a class or a struct | yes | | an element of an `Array`, `Dictionary` or `Set` | yes | | a value captured by a closure (default capture) | yes | | a property or variable declared `weak` or `unowned` | no | | an `Unmanaged` value | no — you manage that count by hand | `let` versus `var` changes whether the binding can be reassigned, not how strongly it holds the object. A `let` constant is exactly as strong as a `var`. ## Where retains and releases come from There is no collector thread and no runtime scan. The **compiler** decides, at compile time, where counts change: - storing or copying a reference inserts a **retain** — built with `-O`, `slot = newBox` compiles to a call to `swift_retain` for the new object and `swift_release` for the old one; - overwriting a reference, assigning `nil`, or a variable reaching the end of its life inserts a **release**; - the optimizer then removes retain/release pairs it can prove unnecessary, so the number of calls in a release build is usually lower than a naive count of copies. Because the decisions are made in the code itself, the counting runs at exactly the points your program copies and drops references. ## When deinit runs The sequence when a reference is released is fixed: 1. The release decrements the strong count. 2. If that release brought the count to zero, the instance's `deinit` runs **right there, synchronously**, on the thread that performed the release. A plain `deinit` does not hop to another thread or wait for a later moment. 3. Only after the `deinit` body finishes are the instance's own stored properties released — which is why a `deinit` can still read them, and why releasing one object can cascade into the deinits of the objects it held. 4. The memory is freed. So in the code example, `print("still alive")` runs while the struct in `upload` still holds the file, and the deinit message appears between `upload = nil` and `print("after release")`. Two practical edges: - A local variable's last release happens after its last use, and the optimizer may move it earlier than the closing brace; don't hang behaviour on the exact line where a local's scope ends. - Objects held by **global variables** may never be deinitialized — the Swift project's own testing guide warns that Swift does not guarantee the destruction of globals, so a deinit is not a shutdown hook. ## Reading the count Swift has no public property or method that returns an object's retain count. The only accessors in the standard library are underscored debugger-support functions such as `_getRetainCount(_:)`, and the number they return depends on what the optimizer kept or removed. In code review and debugging, the reliable signal is behavioural: log from `deinit`, or watch for the deinit you expected and did not see. A missing deinit means some strong reference — another variable, a collection, a struct copy, an escaping closure — still holds the instance. ## The interview answer in one breath Strong by default, everywhere a class reference is stored; structs carry their references but are not counted; the release that reaches zero runs `deinit` on the spot, then frees the instance's properties and memory.

  • A struct that stores a class reference is copied into three array slots; what does that do to the instance's lifetime?
    Each copy of the struct carries its own strong reference, so the instance stays alive until the original and all three elements are gone. Removing the original variable is not enough; clearing the array (or overwriting those properties) is what lets the count reach zero.
  • Does assigning nil to a variable always run the object's deinit?
    Only when that variable held the last strong reference. Another variable, a collection element, a struct copy or an escaping closure that captured the object keeps it alive, and `deinit` runs when the final one is released. A deinit you expected and never saw means something still holds the object.
  • Why can a slow deinit hurt the code that drops the last reference?
    A plain `deinit` runs synchronously inside that release, and the stored properties it then releases may run their own deinits. If the last reference to a large object graph is dropped on the main thread, all of that work happens there, before the next line runs.

  • Structs are reference counted just like classes are
  • A let constant holds the object less strongly than a var
  • Swift runs deinit later, when it next collects garbage
  • Setting one variable to nil always frees the object
  • You can read retainCount in Swift to debug object lifetime
open as a page

In Swift, why do a screen and the view model it owns never deinit when the view model's delegate holds the screen strongly?

level: juniorimportance: must knowfreq 80%

basics

~20 s

Each object keeps the other's strong reference count above zero, so ARC never deallocates either and neither deinit runs. Declaring the view model's delegate as weak var breaks the cycle: the screen is freed first, then the view model it owned.

open as a page

How does Swift's ARC differ from a tracing garbage collector, and what does that buy and cost a Swift app?

level: middleimportance: must knowfreq 60%

basics

~20 s

Swift's ARC compiles retains and releases into the code and frees an instance the moment its last strong reference goes. That buys deterministic deinit and no collector pauses; it costs counting work on every reference copy and leaves reference cycles uncollected.

open as a page

In Swift, when do you declare a back-reference `unowned` instead of `weak`, and what happens if it is read after its object is gone?

level: middleimportance: must knowfreq 72%

basics

~20 s

Use unowned when the referenced object always lives at least as long as the holder, so it never needs to be nil. Reading an unowned reference after its object is destroyed traps; unowned(unsafe) drops that check and reads freed memory.

open as a page

What does Swift's law of exclusivity forbid, and when do two accesses to the same variable conflict?

level: juniorimportance: should knowfreq 30%

basics

~20 s

Swift forbids modifying a variable while another access to it is in progress: two accesses conflict when they hit the same location, are not both reads (or both atomic) and overlap in time. Violations are compile errors or run-time traps.

open as a page

In a Swift loop that imports thousands of images through Objective-C-backed APIs, why does memory climb until the loop ends, and how does autoreleasepool help?

level: middleimportance: should knowfreq 40%

basics

~20 s

On Apple platforms, Objective-C-backed objects can be autoreleased: a pool holds them until it drains, and the enclosing pool may not drain until the loop ends. Wrapping each iteration in autoreleasepool drains them every iteration, so peak memory stays flat.

open as a page

In Swift, why must a `weak` reference have an optional type, and what did Swift 6.3's `weak let` change about it?

level: middleimportance: should knowfreq 40%

basics

~20 s

ARC sets a weak reference to nil when its object is deallocated, so its type must be optional. Weak used to require var; Swift 6.3's weak let (SE-0481) allows an immutable weak property, which a final Sendable class can hold.

open as a page

Why does Swift reject swap(&bodies[i], &bodies[j]) with an overlapping-access error, and how do you update two array elements instead?

level: middleimportance: should knowfreq 35%

basics

~20 s

Passing bodies[i] inout opens a write access to the whole bodies array, so two inout element arguments are two overlapping writes to one variable. Use bodies.swapAt(i, j), or copy both elements into locals, change them and store them back.

open as a page

In Swift, a temporary-file wrapper deletes its file in deinit, yet the file vanishes before the code that reads it; why, and how do you pin its lifetime?

level: seniorimportance: should knowfreq 25%

basics

~20 s

Swift guarantees an object only until its last use, not until the closing brace; a wrapper used as a temporary, as in TempFile(...).url, is freed when that statement ends. Name it and pin it with withExtendedLifetime, or extendLifetime in a defer (Swift 6.2).

open as a page

A Swift autosave controller starts a repeating `Timer` whose block uses `self` and invalidates it in `deinit`; why does `deinit` never run, and how do you fix it?

level: seniorimportance: should knowfreq 50%

basics

~20 s

The run loop retains the scheduled timer, the timer retains its block, and the block captures the controller strongly, so deinit, where invalidate() sits, never runs. Capture self weakly and invalidate the timer on stop or in deinit.

open as a page

A Swift app traps with 'Simultaneous accesses to …, but modification requires exclusive access' — why wasn't this a compile error, and how do you fix it?

level: seniorimportance: should knowfreq 25%

basics

~20 s

Class stored properties, globals and escaping-captured variables are checked at run time because the compiler cannot see every access to them; from Swift 5 on, that check traps in release builds too. Finish the read before the long write starts.

open as a page

In a Swift binary parser, why is returning raw.baseAddress from bytes.withUnsafeBytes and reading the header later a bug, and how should the header be read?

level: seniorimportance: should knowfreq 30%

basics

~20 s

The buffer pointer that Array.withUnsafeBytes passes in is valid only while the closure runs, so a pointer returned from it dangles. Do every read inside the closure and return plain values, using loadUnaligned for packed fields.

open as a page

In Swift, when a function takes a noncopyable database connection, how do `borrowing` and `consuming` parameters differ, and why must you choose one?

level: seniorimportance: should knowfreq 25%

basics

~20 s

A borrowing parameter lends the value for the call and the caller still owns it afterwards; a consuming parameter transfers ownership, so the callee stores or destroys it. Noncopyable parameters have no default, so Swift requires borrowing, consuming or inout.

open as a page

In Swift, how do a `consuming func close()` and `discard self` make a noncopyable database connection close exactly once, even when closing can fail?

level: seniorimportance: should knowfreq 20%

basics

~20 s

Make close() a consuming method so the call ends the caller's binding; inside, close the handle, then discard self so deinit does not close it again. deinit stays as the fallback for connections nobody closed explicitly.

open as a page

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%

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.

open as a page

In Swift, what does marking a database-connection struct `~Copyable` change, and what does the compiler do when you assign it to a second variable?

level: juniorimportance: nice to knowfreq 25%

basics

~20 s

~Copyable removes a struct's implicit Copyable conformance, so each value has exactly one owner. Assigning it to another variable moves it, any later use of the original fails to compile, and its deinit can run only once.

open as a page

What do Swift 6.2's Span and MutableSpan give you over withUnsafeBytes, and why can't a function return the Span of a local array?

level: middleimportance: nice to knowfreq 15%

basics

~20 s

Span is a bounds-checked, non-owning view of contiguous memory that is ~Escapable, so the compiler keeps it inside the lifetime of its source; MutableSpan adds in-place writes. Returning a local array's span would outlive the array, so Swift 6.4 rejects it.

open as a page

In Swift 6.2, how do you build a fixed-size ring buffer of samples on InlineArray, and what changes when its elements are noncopyable?

level: middleimportance: nice to knowfreq 15%

basics

~20 s

Store InlineArray<8, Float>, spelled [8 of Float], keep a write index and wrap it with % count. Copying copies all eight floats eagerly; with a ~Copyable element the InlineArray itself becomes noncopyable and can only move.

open as a page

With Swift's Unmanaged, how do passRetained and passUnretained differ when an object travels through a C callback's void pointer?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

Unmanaged.passRetained adds one strong reference that travels with the pointer, so the object survives until the callback balances it with takeRetainedValue or release. passUnretained adds nothing: something else must keep the object alive, or the callback reads freed memory.

open as a page

What does Swift 6.2's -strict-memory-safety flag report, and what do the unsafe expression and the @unsafe and @safe attributes do?

level: seniorimportance: nice to knowfreq 8%

basics

~20 s

Since Swift 6.2, -strict-memory-safety adds warnings wherever code uses unsafe constructs such as Unsafe pointer types, unowned(unsafe) or unsafeBitCast. Mark each use with an unsafe expression, mark unsafe APIs @unsafe, or declare a type @safe when it hides unsafe storage.

open as a page

In Swift 6, how do you write a generic container or enum that holds a noncopyable connection, and how does switching over it work?

level: seniorimportance: nice to knowfreq 12%

basics

~20 s

Declare Resource: ~Copyable, make the container ~Copyable, and add extension Slot: Copyable where Resource: Copyable. Since Swift 6.0, Optional.take() moves a payload out, and a switch over a borrowed noncopyable enum borrows unless you write switch consume.

open as a page