Daily iOS
Memory and ARC

Deep copy, shallow copy, and COW

In Swift you assign a large array to another variable with var b = a and then modify only b. Is what happens a shallow copy or a deep copy? Explain it together with Copy-on-Write.

How would an interviewer hear this answer? You'll see whether they'd move on, dig in, or say no, and which sentences would trip you up. Your score doesn't change.
See the short answer

At assignment only a shallow copy happens: both variables point at the same heap buffer. The first time b is modified, Swift checks whether the buffer is uniquely referenced and only then copies it in full before writing; that's Copy-on-Write (COW), and if the elements are classes the references in the copied buffer still point at the original instances, so it isn't a complete copy.

Share a question