← All topics/Swift language features

Practical interview questions

Scenario-style prompts with sample answer outlines. Focus is on how you would design and reason in real codebases.

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 behave like value types logically, but they avoid eagerly copying all their storage every time they’re assigned or passed around.

Instead, multiple variables can temporarily share the same underlying storage; the actual copy happens when one of them mutates.

That matters for performance: you get the safety and predictability of value semantics without paying for a full copy on every assignment. In real apps, passing collections around stays much cheaper than people often assume.

Copying still happens when a mutation occurs on shared storage. If two arrays share a backing buffer and one changes, Swift must split that buffer first so the other still sees the old value.

Copying can also happen when bridging to Objective-C, when storage grows or reallocates, or when an operation forces a new buffer.

Principles

  • Arrays and dictionaries are value types.
  • Their storage is shared until mutation.
  • Mutation triggers a real copy if storage is still shared.
  • Copy-on-Write improves performance without giving up value semantics.
  • It is cheap to pass collections around until someone mutates.
  • Large mutations or repeated copies can still get expensive.

After var b = a, both can share storage. After b.append(4), Swift copies so mutating b does not change a.

Shared storage until mutation
var a = [1, 2, 3]
var b = a   // no full copy yet

b.append(4) // b gets its own storage; a unchanged