Question 8
Copy-on-write in standard library collections
What is copy-on-write for Array and Dictionary? Why does it matter for performance and when does copying still happen?
Answer outline
Copy-on-write means Array and Dictionary logically behave as value types but don't copy their storage every time they're assigned or passed around.
Several variables can share the same underlying buffer. The real copy happens only when one of them mutates, and only if the buffer is still shared at that moment.
That's why passing collections around is far cheaper than people assume. You keep the safety and predictability of value semantics without paying for a full copy on every assignment.
Copying still happens when a mutation hits shared storage: Swift duplicates the buffer first so the other variable keeps seeing the old value. It can also happen when bridging to Objective-C, when storage grows or reallocates, or when an operation forces a new buffer.
Principles
ArrayandDictionaryare value types whose storage is shared until mutation.- A mutation copies the buffer only when another variable still shares it, so a uniquely owned array mutates in place.
- Copy-on-write gives you cheap passing and value semantics at the same time.
- Repeated copies in a loop or large mutations on shared buffers can still cost real time, so watch hot paths.
After var b = a both variables share storage, and b.append(4) triggers the copy so a is unchanged:
var a = [1, 2, 3]
var b = a // no full copy yet
b.append(4) // b gets its own storage, a is unchanged



