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?
answer
- value type vs reference type
- assignment and passing
- each screen holds its own cart
- === answers: same instance?
basics
~20 sA 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 sSwift 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 linesstruct 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()) // falsego deeper
Recall that struct, enum and tuple values are copied on assignment and passing, while a class variable holds a reference to one shared instance.
Explain the cart scenario both ways and prove sharing with ===, noting that === only accepts class instances and compares identity, not contents.
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.
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.