DevPrep

All topics › The Swift Language

What is copy-on-write (CoW)?

Middle PRO

The idea

Copy-on-write is an optimization of value semantics: assignment copies only a reference to the buffer, not the data, and a real copy is made before the first mutation if the buffer is shared by several owners. From the outside it looks like a genuine value copy, but a cheap one.

Array, Dictionary, Set, String and Data work this way: they wrap a class-based buffer, and the struct itself is a small wrapper holding a reference.

var x = [1, 2, 3]
var y = x          // O(1): shared buffer
y.append(4)        // O(n) here: the buffer is copied before mutation
print(x, y)        // [1, 2, 3] [1, 2, 3, 4]

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store