skip to content

Copy Semantics and Identity

Structs copy on assignment and classes share one instance, which changes what let means and who sees a mutation. Interviewers ask when you pick a class and how copy-on-write works.

on this pageshow

explore

questions

5

In Swift, if a shopping cart passed to two screens is a struct rather than a class, what happens when one screen adds an item?

level: juniorimportance: must knowfreq 85%

answer

  1. value type vs reference type
  2. assignment and passing
  3. each screen holds its own cart
  4. === answers: same instance?

basics

~20 s

A struct is copied whenever it is assigned or passed, so each screen holds its own cart and the other screen never sees the new item. A class instance is shared, so both screens see it.

solid answer

~50 s

Swift structs and enums are **value types**: assigning one to another variable, passing it to a function or initializer, or storing it in a property produces an independent copy, so a mutation through one variable is never observed through another. Classes are **reference types**: the variable holds a reference, so `let checkoutRef = listScreenRef` is a second name for the same instance and `listScreenRef === checkoutRef` returns `true`. With a struct cart the two screens diverge, which suits a draft the user may discard; to share an edit you hand the new value back to a single owner. With a class cart every screen sees every edit at once, which is convenient and is also where "who changed my cart?" bugs come from. `String`, `Array` and `Dictionary` are structs too and copy the same way.

code

swift · 14 lines
swift
struct CartValue { var items: [String] = [] }
final class CartObject { var items: [String] = [] }

var listScreenCart = CartValue()
var checkoutCart = listScreenCart          // independent copy
checkoutCart.items.append("Milk")
print(listScreenCart.items.count, checkoutCart.items.count)   // 0 1

let listScreenRef = CartObject()
let checkoutRef = listScreenRef            // same instance, second name
checkoutRef.items.append("Milk")
print(listScreenRef.items.count, checkoutRef.items.count)     // 1 1
print(listScreenRef === checkoutRef)                           // true
print(listScreenRef === CartObject())                          // false

go deeper

for a junior

Recall that struct, enum and tuple values are copied on assignment and passing, while a class variable holds a reference to one shared instance.

for a middle

Explain the cart scenario both ways and prove sharing with ===, noting that === only accepts class instances and compares identity, not contents.

for a senior

Tie the choice to bugs you have seen: shared class models mutated from far-away code, or struct copies that silently went stale because nobody wrote the change back.

for a principal

Frame the copy-or-share choice as a data-ownership decision: which component owns the cart, and how do edits flow back to that single owner.

## Two kinds of types Every Swift type falls on one side of a line that decides what happens when a value moves: - **Value types** — every `struct`, every `enum` and every tuple. The book's definition: a value type is one whose value is *copied* when it is assigned to a variable or constant, or passed to a function. - **Reference types** — every `class` (and, outside this lesson, actors and closures). A variable of class type holds a *reference* to an instance that lives elsewhere; copying the variable copies the reference, not the instance. The standard library's everyday types — `Int`, `Double`, `Bool`, `String`, `Array`, `Dictionary`, `Set` — are structs, so they behave like your own structs. ## What a copy means for the cart Imagine a product list screen and a checkout screen that both receive the same cart. 1. **The cart is a struct.** The checkout screen receives its own copy at the moment the cart is passed. Appending `"Milk"` there mutates only that copy. The list screen still shows the cart it had before. If the list screen must reflect the change, the new value has to travel back — returned from a function, handed to a callback, or written into a single owner that both screens read from. 2. **The cart is a class.** Both screens hold references to one instance. Appending `"Milk"` on checkout is visible on the list screen immediately, with no extra plumbing. Neither outcome is a bug in itself: the question is which one you *meant*. A struct gives each holder a stable value that nobody else can change underneath it. A class gives you one shared, mutable thing — and the cost the book points out: when two references are far apart in the code, it is hard to find every place that changes the instance. ## Checking for sharing with `===` Swift's **identity operators** `===` and `!==` answer one question: do these two references point at exactly the same class instance? They are declared in the standard library as taking `AnyObject?` operands, so: - `listScreenRef === checkoutRef` is `true` after `let checkoutRef = listScreenRef`. - A freshly created instance with the same contents is **not** identical: `===` compares identity, not contents. Content equality is `==`, which a type gets by conforming to `Equatable`. - Two `nil` optionals compare as identical. - Applied to two struct values, `===` does not compile: the compiler reports that the argument type is *expected to be an instance of a class or class-constrained type*. Struct values have no identity to compare — only contents. ## Copies are a semantic promise The rule is about what your code can **observe**, not about how many bytes move. The standard library's collections share their element storage between copies and copy it only when one copy is modified, so passing a large array is cheap; the observable behaviour is always as if a copy had taken place immediately. How the collections do this is covered in the material on arrays, sets and dictionaries; what matters here is that you can reason about a struct cart as if every screen had its own. | Situation | Struct cart | Class cart | |---|---|---| | `var b = a` | `b` is an independent copy | `b` refers to the same instance | | Append an item through `b` | `a` is unchanged | `a` sees the item | | `a === b` | does not compile | `true` | | Who can change the cart? | only the variable holding it | every holder of a reference | ## Enums follow the same rule An `enum` value — including one with associated values — is copied exactly like a struct. If a `CheckoutState.active(count: 1)` is assigned to another variable and the original is later reassigned to `.empty`, the second variable still holds `.active(count: 1)`. ## What to say in the interview - Name the two categories and which keywords fall in each. - Describe the observable difference for the scenario: diverging carts vs shared edits. - Mention `===` as the way to prove two variables share a class instance, and that it rejects struct values at compile time. - Close with the design choice: a struct when each screen should own its data, a class (or a single owner of a struct value) when everyone must see one source of truth.

  • Can you use `===` to check whether two struct variables share storage?
    No. `===` is declared with `AnyObject?` operands, so the compiler rejects struct values with "argument type ... expected to be an instance of a class or class-constrained type". A struct value has no identity to compare; if you need to compare contents, conform the type to `Equatable` and use `==`.
  • If a struct cart is passed to a function, can that function change the caller's cart?
    Not through an ordinary parameter: the function receives its own value, and parameters are constants, so assigning to a property of it does not compile. To change the caller's value the parameter must be declared `inout`, which the material on parameters covers, or the function returns a new cart for the caller to store.

A struct cart is a photocopy handed to each screen: writing on one copy leaves the other untouched. A class cart is a shared link to one document: an edit through any link shows up for everyone holding it.

  • Assigning a class instance to a new variable makes a copy of the object.
  • Structs are copied on assignment but enums are shared like classes.
  • The === operator compares the contents of two instances, the same as ==.
  • Swift arrays are references, so two struct copies share their array of items.
  • Passing a struct cart to a function lets that function change the caller's cart.
open as a page

In Swift, what does `let` freeze when the constant holds a struct value, and what does it freeze when it holds a class instance?

level: middleimportance: must knowfreq 70%

basics

~10 s

A let struct is entirely immutable: no property can be assigned, even one declared var. A let class reference cannot be pointed at another instance, but the instance's var properties can still change.

open as a page

In Swift, how do you give a large Matrix struct copy-on-write behaviour with a class box and `isKnownUniquelyReferenced(_:)`, and what breaks it?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Keep the elements in a private class instance; in every mutating method call isKnownUniquelyReferenced(&storage) and, when it returns false, replace the box with a clone before writing. Copies share the box until one of them writes.

open as a page

In Swift, a Cart struct stores a Coupon class instance; after copying the cart and changing the coupon's discount on the copy, why does the original cart change too?

level: seniorimportance: should knowfreq 55%

basics

~20 s

Copying a struct copies each stored property, and a class-typed property is a reference, so both carts point at the same Coupon. Value semantics stops at that reference; changes to the coupon show through every copy.

open as a page

As a lead setting a Swift team rule of structs by default for models, where would you still require a class, and what does the rule cost?

level: principalimportance: should knowfreq 50%

basics

~20 s

Default model types to structs and enums, and require a class when identity is the point: one shared mutable instance, inheritance, Objective-C exposure, a weak reference, or deinit cleanup. The rule costs explicit ownership and write-back plumbing.

open as a page