Swift's Array, Set and Dictionary are value types, so when does assigning or passing one actually copy its elements?
answer
- copies share one buffer
- the first write pays
- uniquely referenced storage
- extract, mutate, write back
basics
~20 sAssigning, passing or returning a standard collection copies only a reference to its shared storage. The elements are copied when a mutation hits storage that another copy still shares; a uniquely owned buffer is mutated in place.
solid answer
~40 sSwift's collections use **copy-on-write**. A copy, whether by assignment, a function argument or a stored property, shares the original's element buffer, so it costs O(1). The element copy happens on the first mutation through a variable whose buffer is shared: that variable gets its own buffer, O(n), and later mutations are in place. A buffer with one owner is mutated in place; it is only reallocated when it must grow past its capacity. The classic trap is pulling a value out of a container into a local `var`, mutating it and writing it back: the container still holds the buffer, so the mutation copies it. Mutating in place with `dict[key]!.append(x)` or `dict[key, default: []].append(x)` avoids that. If the elements are class instances, a copy duplicates references, not the objects.
code
swift · 23 linesfunc address(_ a: [Int]) -> UnsafeRawPointer? {
a.withUnsafeBufferPointer { UnsafeRawPointer($0.baseAddress) }
}
var cache: [String: [Int]] = [:]
var ids: [Int] = []
ids.reserveCapacity(2_000) // spare room, so growth never reallocates
ids.append(contentsOf: 0..<1_000)
cache["trip"] = ids
ids = [] // the dictionary is now the only owner
let start = address(cache["trip"]!)
cache["trip"]!.append(1_000) // in place: unique buffer, spare capacity
print(address(cache["trip"]!) == start) // true
cache["trip", default: []].append(1_001) // also in place
print(address(cache["trip"]!) == start) // true
var trip = cache["trip"]! // a second owner of the same buffer
trip.append(1_002) // the write copies all 1,002 elements
cache["trip"] = trip
print(address(cache["trip"]!) == start) // falsego deeper
Remember that arrays, sets and dictionaries behave as independent copies, and that the real element copy is delayed until one of the copies is changed.
Explain the uniqueness check before each mutation, why the first write after sharing is O(n), and why class elements are shared even after the array copies.
Find hidden buffer copies in hot paths, such as extract-mutate-write-back on dictionary values or snapshots kept alive, and rewrite them as in-place mutations.
Weigh the readability of value semantics against hidden copy costs in shared model layers, and decide where profiling, not intuition, should settle the trade-off.
## Value semantics without eager copying In Swift, `Array`, `Set`, `Dictionary` and `String` are structs, so they have **value semantics**: after `var b = a`, changing `b` never changes `a`. Copying every element on every assignment would make that unaffordable, so the standard library uses **copy-on-write** (COW). The Swift book states the rule plainly: these collections share the memory where elements are stored between the original and any copies, the elements are copied just before one of the copies is modified, and the behaviour you see is always as if a copy took place immediately. Under the hood each collection is a small struct holding a reference to a heap-allocated **buffer**. Copying the struct copies that reference and bumps a reference count. ## When the elements are really copied | Operation | Element copy? | |---|---| | `let b = a`, `var b = a` | no, the buffer is shared | | passing `a` as an argument or returning it | no | | storing `a` in a struct property or another collection | no | | passing `&a` to an `inout` parameter | no, unless the buffer is shared | | first mutation of a variable whose buffer is shared | **yes**, O(n), into a new buffer | | later mutations of that variable | no, it now owns its buffer | | any mutation of a uniquely owned buffer | no copy-on-write; in place unless growth reallocates | Before every mutating operation the collection checks whether its buffer is **uniquely referenced**. If it is, it mutates in place; if not, it allocates a new buffer, copies the elements, and mutates the copy. `Array`'s subscript documents this directly: writing is O(1) unless the storage is shared with another array or is a bridged `NSArray`, in which case it is O(n). The documentation also notes that optimizations are sometimes applied that reduce copying, so treat the rule as the upper bound on what you pay. ## The traps that cost real time 1. **Extract, mutate, write back.** `var ids = cache["trip"]!; ids.append(x); cache["trip"] = ids` makes the local `ids` a second owner of the buffer the dictionary holds, so `append` copies the whole array. Mutate through the container instead: `cache["trip"]!.append(x)` or `cache["trip", default: []].append(x)`. 2. **A forgotten snapshot.** Keeping an old copy alive, for undo history or a diff, means the next write to the live array copies everything. That is often correct, but it should be deliberate. 3. **Copies inside a loop.** Assigning an array to a temporary and mutating the original inside a loop can turn an O(n) loop into an O(n^2) one if every iteration re-shares and re-copies. ## Value semantics with class elements COW concerns the buffer, not the objects in it. If `Element` is a class, the buffer stores references: - Copying the array copies those references; both arrays then point at the same objects. - Changing a property of `a[0]` is visible through `b[0]`, because it is one object. - Replacing `a[0]` with a new object only changes `a`, because that is a mutation of `a`'s buffer. The `Array` documentation walks through exactly this case. ## Seeing it for yourself Comparing buffer addresses through `withUnsafeBufferPointer` in a test, as in the code example, shows when sharing ends. Swift 6.4 adds `isTriviallyIdentical(to:)` on the standard collections (SE-0494), documented as O(1), which reports whether two values share the same storage without unsafe pointers; on an older toolchain, the buffer address is the way to observe it. ## A review checklist When a profile shows time in array or dictionary copies, these are the questions to ask of the code: - Is a collection read out of a container, mutated, and written back? Mutate it through the container instead. - Is an old copy kept alive longer than needed, such as a snapshot captured for logging or diffing? Drop it before the hot mutation. - Is a large collection captured by a long-lived closure or stored in a second struct that outlives the work? Every capture is another owner. - Are elements class instances that the code expects to be independent after a copy? Copy-on-write will not clone them; that needs an explicit copy of each object. - Is the cost real? Measure with Instruments before rewriting, because the optimizer already removes some copies. ## What belongs elsewhere Implementing the same behaviour for your own struct with `isKnownUniquelyReferenced(_:)` is covered in the lesson on copy semantics and identity; this lesson is about what the standard collections already do and what that costs your code.
- Does passing a large array to a function that only reads it copy the elements?No. The parameter shares the caller's buffer, so the call is O(1). Copying would only happen if the function assigned the parameter to a `var` and mutated that `var` while the caller still held the buffer.
- How can a test show that two arrays share storage?Compare `withUnsafeBufferPointer { $0.baseAddress }` of both arrays, or on Swift 6.4 call `isTriviallyIdentical(to:)`, which is O(1) and compares storage identity. Equal storage implies equal contents; equal contents do not imply shared storage.
- Why does a dictionary of arrays update faster with `dict[key, default: []].append(x)` than with read, modify and assign?The default subscript yields the stored array for in-place mutation, so when the dictionary is its only owner the append runs without copying. Reading it into a local `var` first creates a second owner, and the append then copies the whole array.
Copy-on-write is like colleagues reading one shared printout: nobody photocopies it until someone wants to write on it, and only that person gets the fresh copy to scribble on.
- Saying every assignment of an array copies all its elements
- Saying arrays are reference types because copies share memory
- Thinking mutating a uniquely owned array still copies it
- Believing copying an array of class instances clones the objects
- Reading a dictionary value into a var, mutating, and writing it back as free
Copy-on-write behaves the same in every Swift release; isTriviallyIdentical(to:), mentioned for observing shared storage, arrived in Swift 6.4 (SE-0494).