Member-only story
Understand Copy-on-Write in Swift 5
Structs, value types, and dark magic

In this article, we will find out what copy-on-write is and why it’s absolutely awesome. We will also learn how it works and how we can implement our own custom objects with copy-on-write behavior.
What Is Copy-on-Write?
Copy-on-write is the magic behind value types. For starters, consider the following simple example:
var x = ["a", "b", "c"]
let y = x
x.append("d")
print(x) //["a", "b", "c", "d"]
print(y) //["a", "b", "c"]
As you probably already know, collections like Array have value semantics.
What that means is that unlike reference types, which store a reference to the object, value types store a copy of it. In the above example, y
gets a copy of x
.
Each time you assign a value type to a variable, a copy gets made. This sounds super expensive, how can stuff like this happen in Swift?
Well, thanks to copy-on-write, it’s actually not that expensive.
Behind the scenes, both of these arrays contain a reference to a memory location where the actual array is stored. At this point, both x
and y
point to the same place.