DevPrep

All topics › Modern Swift

value type vs reference type — how to choose?

Middle PRO

The idea

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

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store