Objects and references
Essence
In classic OOP an "object" almost always means a reference type: a variable stores an address, several variables may point at the same object, and a change through one is visible through the other. In Swift that is only half the story: there are reference types (class, actor, closures) and value types (struct, enum, tuples), and choosing between them is a key design decision.
Example
final class Node { var value: Int; init(_ v: Int) { value = v } }
struct Point { var x: Int }
let n1 = Node(1)
let n2 = n1 // same object, retain count 2
n2.value = 42
print(n1.value) // 42 — shared state
print(n1 === n2) // true — identity, not equality
var p1 = Point(x: 1)
var p2 = p1 // independent copy
p2.x = 42
print(p1.x) // 1
final class Parent { var child: Child? }
final class Child { weak var parent: Parent? } // breaks the cycle
let parent = Parent()
parent.child = Child()
parent.child?.parent = parent
Reference types
- Have identity:
===compares addresses,==compares contents (if the type isEquatable). - Live under ARC: each strong reference increments the count; the object is freed at zero. Two objects holding each other strongly form a retain cycle, a leak. Break it with
weak(Optional, becomes nil) orunowned(non-Optional, crashes if the object is gone). leton a class fixes the reference, not the contents:let node = Node(1); node.value = 2is allowed.
Value types
- Copied on assignment and when passed;
letmakes the value fully immutable;mutatingmarks methods that changeself. - No identity and no ARC overhead for "pure" structs (a struct holding a class field still does retain/release on copy).
- Large structs (
Array,String) use copy-on-write, so a copy is cheap.
What the interviewer looks for
- When to use a class: identity is needed, shared mutable state, inheriting from UIKit, an object with a lifecycle (
deinit). - When to use a struct: data, models, DTOs, anything that should be
Sendablefor free. - Closures are reference types too: capturing
selfin an escaping closure creates a strong reference, hence[weak self].