What is copy-on-write? Which types use it?

1.1.7 · L2 · Interview

Reported at: Flipkart

Predict first

How many times is the element buffer copied?

var a = [1, 2, 3]
var b = a
b.append(4)
b.append(5)
  • 0
  • 1
  • 2
  • 3

Mental model. COW is a shared Google Doc that silently forks the moment you type — readers share, writers get their own copy.

Copy-on-write delays the actual buffer copy until a unique reference is about to mutate. On assignment, both values point at the same heap buffer with a reference count of 2. On write, the type checks isKnownUniquelyReferenced; if the buffer is shared it copies first, then mutates.

Array, Dictionary, Set, String, and several Foundation value types use it. Your own struct does not unless you implement it yourself with an internal reference-type buffer.

var b = a shares the buffer. The first append sees two owners and copies once. After that b is the unique owner, so the second append mutates in place.

Common traps

  • “Array always copies on mutation.” No — if it is uniquely referenced it mutates in place. That is why COW is fast in the common case.
  • “My struct is automatically COW.” No. A struct containing a large Array gets COW only for that array; the struct itself is still copied (cheaply — three words).

They might follow up with

  • How would you implement COW for your own type? Store a final class buffer, check isKnownUniquelyReferenced(&buffer) inside every mutating method, copy the buffer if it is shared.
  • What is the danger of isKnownUniquelyReferenced? It only tells you about strong references — a buffer held only by a weak or unowned reference can still be uniqued.

Related questions

  • 1.1.1 What is the difference between a value type and a reference type in Swift? When do you choose each?
  • 1.1.3 Where do value types live — stack or heap?

← When is teaching “always use structs” harmful on a team?   What is Never? Where do you see it? →