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?
answer
- what does a struct copy copy?
- memberwise copy of stored properties
- the reference is the property
- prove it with ===
basics
~20 sCopying 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.
solid answer
~40 sA struct copy is a **memberwise** copy of its stored properties. `items` is an `Array`, a value, so the copies diverge; `coupon` is a reference to a class instance, so both carts now hold the same `Coupon`, and `checkoutCart.coupon === draftCart.coupon` is `true`. Writing `draftCart.coupon.percentOff = 50` mutates that one object, and `checkoutCart` sees 50 even though it is a `let` constant, because `let` froze the cart's stored reference, not the object. Fixes, in order of preference: make `Coupon` a struct; make it an immutable class (`final`, every property `let`) so sharing is harmless; or keep the class private and copy it before writing, which is the copy-on-write pattern. Such a struct is also no longer implicitly `Sendable`.
code
swift · 18 linesfinal class Coupon {
var percentOff: Int
init(percentOff: Int) { self.percentOff = percentOff }
}
struct Cart {
var items: [String]
var coupon: Coupon
}
let checkoutCart = Cart(items: ["Milk"], coupon: Coupon(percentOff: 10))
var draftCart = checkoutCart // copies the struct, shares the Coupon
draftCart.items.append("Bread") // only draftCart changes
draftCart.coupon.percentOff = 50 // both carts see 50
print(checkoutCart.items.count, checkoutCart.coupon.percentOff) // 1 50
print(draftCart.items.count, draftCart.coupon.percentOff) // 2 50
print(checkoutCart.coupon === draftCart.coupon) // truego deeper
Recall that copying a struct copies its stored properties, and a property of class type is copied as a reference, not as a new object.
Walk through the copy step by step, showing which property diverges and which is shared, and prove it with === on the class-typed property.
Show the diagnosis you would run on a real bug, then choose the fix from what the inner type is: data, immutable shared configuration, or heavy storage behind copy-on-write.
Turn it into a review rule: model structs hold value-typed properties, and any class-typed property is either immutable, private behind copy-on-write, or documented as shared.
## The symptom A checkout flow keeps a `Cart` struct. A "draft" screen copies the cart so the user can experiment, adds an item and applies a bigger discount. When the user backs out, the item is gone from the real cart as expected — but the discount stuck. The struct looked like a value, yet one of its parts behaved like shared state. ## What copying a struct actually copies Copying a struct — by assignment, by passing it, by storing it — copies **each stored property** of the struct: - A property whose type is a **value type** (`Int`, `String`, `Array`, another struct, an enum) is copied as a value, so the two structs diverge from then on. - A property whose type is a **class** holds a **reference**. Copying it copies the reference, so both structs now refer to the *same* instance. Nothing is deep-copied. Swift never follows a reference and duplicates the object behind it. The struct is a value type, but its **value semantics are only as deep as its properties are values**. ## Tracing the cart step by step 1. `let checkoutCart = Cart(items: ["Milk"], coupon: Coupon(percentOff: 10))` creates one cart and one `Coupon` object. 2. `var draftCart = checkoutCart` copies the cart: a second `items` array value and a second reference to the same `Coupon`. 3. `draftCart.items.append("Bread")` changes only `draftCart.items`. 4. `draftCart.coupon.percentOff = 50` reads the reference out of `draftCart` and writes to the shared object. 5. `checkoutCart.coupon.percentOff` is now 50, and `checkoutCart.coupon === draftCart.coupon` prints `true`. Note step 4 compiles even against a `let` cart: `let` freezes the stored reference, not the object it points to. ## Diagnosing it - Compare the class-typed properties with `===`. `true` means two struct copies share the object; `==` would compare contents, if the class is `Equatable` at all. - `===` on the struct values themselves does not compile — a struct has no identity — so check the class-typed property, not the struct. - Search the struct for stored properties whose type is a class, a class-bound protocol existential, or a closure; each is a path to shared state. ## Ways to fix it | Fix | When it fits | What it costs | |---|---|---| | Make the inner type a struct | The coupon is plain data | Changes to it must be written back through the cart | | Make the class immutable (`final`, all `let`) | The object is shared configuration or a cache key | To change a value you create a new instance | | Private class plus copy before write | Large or non-value storage you must keep in a class | Every write path must check and clone | | Accept and document sharing | The reference is a service or logger, not data | Readers must know it is not part of the value | The third row is the copy-on-write pattern: the class is a `private` implementation detail and every mutating path clones it when it is shared, so callers can never observe the sharing. ## Other routes to the same leak A class-typed stored property is the common case, but not the only one. The same sharing appears whenever a value carries a reference: - An **enum case with an associated value of class type** — copying the enum copies the reference. - A stored **closure** that captured a class instance or a variable — closures are reference types, and copies of the struct share what the closure captured. - A property typed as a **class-bound protocol** (one inheriting from `AnyObject`) — every conforming type is a reference type, so the property holds a reference. ## Side effects beyond the bug - A struct that is not `public` and whose stored properties are all `Sendable` is implicitly `Sendable`; one non-`Sendable` class property removes that inference. The concurrency material covers what that blocks; compiling in Swift 6 language mode is where it surfaces as errors. - Exposing the class-typed property publicly, even as `private(set)`, still lets callers mutate the shared object through the getter; `private(set)` only stops them from replacing the reference. ## What a strong answer sounds like - States that a struct copy is a memberwise copy and that a class-typed property copies as a reference. - Proves the sharing with `===` on the property, not on the struct. - Picks a fix by asking what the inner type really is: data (make it a value), shared configuration (make it immutable), or heavy storage (hide it behind copy-on-write).
- Would declaring `coupon` with `let` inside `Cart` fix the bug?No. A `let` property freezes which `Coupon` the cart refers to, but `Coupon`'s own `var percentOff` stays writable through that reference, so `draftCart.coupon.percentOff = 50` still compiles and both carts still see it. Only making the coupon a value, making the class immutable, or cloning it before writes restores value semantics.
- When is a class-typed property inside a struct perfectly fine?When the object is immutable — a `final` class whose properties are all `let` — so sharing it cannot be observed, or when the reference is deliberately not part of the value, such as an injected service or logger, and the type documents that. It is also fine as a private copy-on-write box whose every write path clones it when it is shared.
- Does marking the struct's class-typed property `private(set)` stop callers from changing the coupon?Only its replacement. `private(set)` restricts the setter, so outside code cannot assign a new `Coupon`, but the getter still hands out the reference, and `cart.coupon.percentOff = 50` compiles from outside the type. To protect the object you hide the property entirely and expose values, or make the class immutable.
- Copying a struct deep-copies every object its properties refer to.
- Declaring the cart with let stops the coupon's discount from changing.
- Marking the Coupon class final gives it value semantics.
- You can call === on the two cart structs to see whether they share state.
- private(set) on the coupon property keeps outside code from changing the discount.