What is copy-on-write (CoW)?
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