value type vs reference type — how to choose?
The idea
- Value types (
struct,enum, tuples,Array/String/...) — each variable has its own copy; changing one does not affect another. No identity, no inheritance, nodeinit. They live on the stack or inside their owner, and need no ARC (if they contain no references). - Reference types (
class,actor, closures) — variables share one heap object; it has identity (===), a reference count,deinit, inheritance (for classes).
struct Point: Sendable { // no references — Sendable for free
var x: Double, y: Double
}
final class Canvas { // identity: one canvas, many references
var points: [Point] = []
}
var a = Point(x: 0, y: 0)
var b = a // copy
b.x = 1
print(a.x, b.x) // 0.0 1.0
let c1 = Canvas()
let c2 = c1 // same reference
c2.points.append(a)
print(c1.points.count) // 1
struct Model { // trap: a value type with a class inside
var canvas = Canvas() // copies of Model share one Canvas
}
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep