Better Programming

Advice for programmers.

Follow publication

Member-only story

Understand Copy-on-Write in Swift 5

Structs, value types, and dark magic

Lajos Deme
Better Programming
Published in
4 min readMar 3, 2020

--

Photo by Giammarco Boscaro on Unsplash

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.

--

--

Lajos Deme
Lajos Deme

Written by Lajos Deme

Founder of www.mercuryprotocol.io | We're building the world's data marketplace

No responses yet

Write a response