Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 146 ยท Structures, Classes and Enums

Value vs. Reference Semantics

Understand Swift value and reference semantics - copies versus shared instances, identity versus equality, copy-on-write, isKnownUniquelyReferenced, and how to choose struct, class or actor.

Every type you design in Swift makes a quiet promise about what happens when you write let b = a. Either b becomes an independent copy of a, or b becomes a second name for the same object. The first promise is called value semantics, the second reference semantics. Getting this choice right removes whole families of bugs; getting it wrong produces the kind of bug where changing one screen's data mysteriously changes another's.

You already met the two building blocks in Structures and Classes. This lesson steps back and treats the choice as a design decision. You will learn to see the difference in running code, to separate identity from equality, to build a value type that wraps a reference with copy-on-write, and to decide between struct, class and actor.

The core difference in one example

A struct is copied on assignment. A class instance is shared. The same two lines of code behave differently:

Swift Copy or share

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

After the struct copy, changing b leaves a alone, so the first line prints struct: 1 99. With the class, c and d are two variables holding one reference, so the write through d is visible through c: class: 99 99.

Notice that c is declared with let and we still changed c.x. For a class, let freezes the reference (you cannot make c point elsewhere), not the object it points to. For a struct, let freezes the whole value, so a.x = 5 on a let a is an error.

What a value type really guarantees

The practical promise of value semantics is local reasoning. If a function receives a struct, nothing it calls can change the caller's copy behind its back. You can read a function and know exactly which variables it can affect. With reference types, any code that holds the reference can mutate the shared object at any time, so you must read much more code to know what a value is.

The standard library follows the value-type rule: Int, String, Array, Dictionary, Set and Optional are all structs, so var copy = original on an array gives you an independent array. Foundation's Data, Date, URL and UUID are value types too.

A trap: value types that contain references

A struct copies its stored properties, and a stored property that holds a class instance copies only the reference. The struct itself is a value, but part of its state is shared.

Swift A struct that smuggles in sharing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The names are independent (first and second), but both widgets report a count of 5 because there is only one Counter. This is why people say "a struct is only as much of a value as its parts". When you design a struct, check every stored property: is it itself a value type? If not, either make it one, or hide the reference behind an API that keeps the value promise (see copy-on-write below).

Identity versus equality

Two different questions hide behind "are these the same?":

  • Equality asks whether two values are interchangeable: same contents. It is written == and needs Equatable.
  • Identity asks whether two references point to the same object in memory. It is written === (and !==) and exists only for classes.
Swift === versus ==

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

first and second are equal but not identical, while first and alias are identical. Once alias changes the balance, first and second stop being equal, because first and alias are literally the same object.

Value types have no identity. Two Point(x: 1, y: 2) values are the same thing, in the way two copies of the number 7 are. That is why === does not compile for structs: the question has no meaning.

Use identity when the object is something in the world: a database connection, a window, a file handle, a network session. Use equality when the data is just data: a coordinate, a price, a date range.

Copy-on-write: cheap copies for big values

If var b = a really copied a million-element array, Swift programs would be slow. They are not, because Array, String, Dictionary and Set use copy-on-write (COW). A copy initially shares the same storage; the real duplication happens only when one side is mutated.

You can build the same technique yourself. The recipe has three parts: a private final class holding the data, a struct that holds a reference to it, and an isKnownUniquelyReferenced check before every mutation.

Swift Your own copy-on-write type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Assigning b = a copied nothing. The first mutation through b noticed that two Bag values shared one Storage, duplicated it, and only then appended. After that b owned its storage, so the next add was free. The array a was never disturbed.

Three details matter in real code:

  • isKnownUniquelyReferenced needs an inout reference to a class instance, which is why the property is a var and is passed with &.
  • Every mutating method must run the check. One forgotten path silently breaks value semantics.
  • The storage class should be private and final. If outside code could grab the reference, uniqueness checks would be meaningless.

You rarely write this yourself. Most of the time, build your struct out of Array, String and friends and you inherit their copy-on-write for free. Reach for a custom COW type only when wrapping a large buffer, a C resource or a class that you want to expose as a value.

Choosing: struct, class or actor

Start from what the type is, not from habit.

Use a... When...
struct The data is a value: a point, money, a settings record, a parsed result. Equality by contents makes sense. Copies should be independent. This is the default.
class The thing has identity or a lifetime you must manage (connection, cache, observable model), you need inheritance, or several owners must see one shared mutable state.
actor Several tasks need to share mutable state safely. An actor is a reference type whose state is protected from data races. See the concurrency lessons.
enum A value that is exactly one of a fixed set of cases. Enums are value types too.

A good test: "If I copy this and change the copy, should the original change?" If the answer is "no", it wants to be a value. If it is "yes, they are the same thing", it wants to be a class (or an actor if tasks share it).

Why Swift 6 pushes you toward values

Swift 6 checks data races at compile time. Value types that contain only other value types are automatically Sendable: they can cross task boundaries safely because every task gets its own copy. A mutable class with shared state cannot cross, and the compiler says so:

Swift A mutable class is not Sendable (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler rejects the first Task.detached with main.swift:12:5: error: non-Sendable type 'Settings' of let 'settings' cannot exit main actor-isolated context, plus a note that class 'Settings' does not conform to the 'Sendable' protocol. (A plain Task { } in top-level code would inherit the main actor and compile, which is why the example uses Task.detached.) The struct passes without complaint. The fixes are to turn Settings into a struct, to make it an actor, or to protect its state with a lock (see the Synchronization lesson). Value semantics is the cheapest of the three.

Passing values to functions

Function parameters are constants inside the function, and a struct passed in is a copy (or, thanks to optimizations, behaves as if it were). To let a function change the caller's value, use inout and &:

Swift inout and value types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first function leaves s untouched and returns a new value, so s: 0 bonus: 10. The second modifies s in place. Prefer returning new values for clarity; use inout when mutating in place avoids a copy or reads more naturally.

Common pitfalls

  • Large structs are not slow to pass. Copying a struct with a few fields is a few machine words. Collections copy lazily. Do not switch to a class "for performance" without measuring.
  • Classes in arrays: an array of class instances copies the references, so var b = a shares the objects inside. Mutating b[0].x changes a[0].x too.
  • Equatable on classes: if you implement == on a mutable class, a value stored in a Set or used as a dictionary key can change its hash. Prefer immutable classes (let properties) or identity-based equality.
  • Mixing styles: a struct with a class property (the Widget trap above) gives readers the wrong picture. Either commit to a value or document the sharing.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. After var b = a where a is a struct instance, you change b.x. What happens to a.x?

    Structs have value semantics: assignment copies the value, so the two variables are independent.
  2. 2. What does === test?

    === is the identity operator and is defined for class instances. Equality of contents is ==, which needs Equatable.
  3. 3. In a copy-on-write type, when is the storage actually duplicated?

    Copies share storage until one of them mutates. isKnownUniquelyReferenced tells the type whether it must duplicate first.
  4. 4. Which type is the best default choice for a plain data record such as a price or a coordinate?

    Data with no identity and where copies should be independent is a value, so a struct is the default.
  5. 5. Why does a Widget struct that stores a Counter class instance not behave like a pure value?

    A stored reference is copied as a reference. Both struct copies then point at the same Counter instance.

Summary

  • Structs, enums and tuples have value semantics: assignment copies. Classes and actors have reference semantics: assignment shares.
  • let on a class freezes the reference, not the object. let on a struct freezes the entire value.
  • == compares contents (Equatable); === compares identity and works only for classes.
  • A struct that stores a class instance shares that instance between copies. Keep value types made of values.
  • Copy-on-write gives value semantics with cheap copies: share storage, and duplicate only before a mutation when isKnownUniquelyReferenced says it is shared.
  • Start with a struct. Choose a class for identity, lifetime or inheritance, and an actor for shared state used by several tasks.

Next: Equatable, Hashable and Comparable