Value types vs reference types

Swift language Junior Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Predict the output

What does this print?

struct PointS { var x = 0 }
final class PointC { var x = 0 }

var a = PointS()
var b = a
b.x = 5

let c = PointC()
let d = c
d.x = 5

print(a.x, c.x)
Options
Hint 1 of 1

Which assignment copies the data?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: B 0 5

Correct. The struct was copied; the class instance is shared by c and d.

Why not the others?
  • A 5 5. b is a copy of a, so changing b doesn't affect a.
  • C 0 0. c and d point to the same object, so the change is visible through c.
  • D It doesn't compile because d is a let. let fixes the reference, not the object's properties.

30-second answer

Value types (structs, enums, tuples) are copied on assignment, so each variable owns its data. Reference types (classes, actors, closures) are shared: assigning copies the reference, and every variable sees the same instance. Prefer structs for data; use classes when you need identity, shared mutable state or inheritance.

Practise saying it · 30 s. No recording, just a timer

Explain value vs reference types.

Say your answer out loud, then check which of these points you covered:

  • Copy vs shared
  • Prefer structs for data
  • let on classes fixes only the reference

Deep dive

Value types are easier to reason about and are naturally thread-safe when immutable.

Standard collections are value types that use copy-on-write to stay cheap.

let on a struct makes the whole value immutable; let on a class only fixes the reference.

Structs holding class references are only shallowly copied.

Common mistakes

  • Thinking let makes a class instance immutable.
  • Using classes for plain data models by default.

Senior take & follow-ups

Seniors connect value semantics to fewer bugs and easier concurrency.

Follow-up questions

Think of your answer first, then open the hint.

  1. When do you need a class?

    Show hint

    Identity, shared mutable state, inheritance, or Objective-C interop.

  2. Is a struct with a class property a value type?

    Show hint

    Yes, but the class part is shared between copies.

Suggest a fix if something here is wrong or out of date.