In Swift, which references keep a class instance alive under ARC, and at what moment does its deinit run?
answer
- only one kind of type is counted
- strong is the default for every binding
- a struct can still own an object
- the release that reaches zero
basics
~20 sEvery 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 sARC 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 linesfinal 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
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.
Explain where strong references hide: struct properties, collection elements and closure captures, and why each struct copy retains the object again.
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.
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