Skip to Content
Course content

25: Value Semantics and Copy-on-Write

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've noticed a recurring pattern when I mentor developers moving from C++ or Java to Swift. They get a handle on the difference between struct and class, but then they hit a wall of performance anxiety. They start worrying that passing a massive array around their app is going to kill the frame rate because, as they've been told, "structs are value types, so they're copied every time."

The "Structs are Slow for Big Data" Myth

The misconception is that if you have an array with 100,000 elements and you assign it to a new variable, Swift immediately duplicates those 100,000 elements in memory. If that were true, Swift would be unusable for high-performance apps. Let's look at what actually happens.

struct UserProfile {
    var username: String
    var bio: String
}

var groupA = [UserProfile](repeating: UserProfile(username: "Dev", bio: "Coding..."), count: 100_000)
var groupB = groupA // Is this a massive, slow copy?

In the code above, the assignment var groupB = groupA is nearly instantaneous. It doesn't matter if the array has ten elements or ten million. Why? Because Swift is lying to you. Or rather, it's being very clever.

How Copy-on-Write Actually Works

Swift uses a technique called Copy-on-Write (CoW). When you assign one collection to another, Swift doesn't copy the actual data. Instead, both variables point to the same memory storage. They share the same underlying buffer.

The "copy" only happens at the exact moment you try to mutate one of them. Here is the mental model: Swift keeps a reference count on the internal storage. As long as only one variable owns that storage, it can be modified in place. The moment a second variable claims ownership, Swift marks the storage as shared. If you then try to change a value in groupB, Swift notices the shared ownership, copies the data to a new buffer, and then applies the change to that new copy.

groupB[0].username = "NewName" // NOW the copy happens.

This gives you the best of both worlds: the safety and predictability of value semantics (meaning groupA won't magically change just because you edited groupB) with the performance of reference types.

Where CoW Stops and Value Semantics Continue

Here is the part where people usually get tripped up again. CoW is not a magic property of all structs. It is an optimization implemented specifically by the Swift Standard Library for collections like Array, Dictionary, Set, and String.

If you build your own custom struct that doesn't wrap one of these collections, you don't get CoW for free. Consider this:

struct BigData {
    var values: (Int, Int, Int, Int, Int) // A large tuple
}

var data1 = BigData(values: (1, 2, 3, 4, 5))
var data2 = data1 // This IS a real, immediate copy.

Because BigData is a simple struct containing a tuple (not a managed collection), Swift performs a bit-for-bit copy of the data on assignment. For small structs, this is incredibly fast—often faster than the overhead of CoW. But if you're building a custom type that manages a massive amount of memory, you'll have to implement your own CoW logic using a private reference-type wrapper. I'll leave that for the advanced architecture discussions, but for now, just remember: value semantics are the guarantee (the data won't change unexpectedly), while CoW is the optimization (we won't copy until we have to).




📋 Practical Task

Implementing a Copy-on-Write Storage Wrapper

To truly understand how the Swift Standard Library implements CoW, you're going to build a simplified version of it. You will create a CustomBuffer struct that manages a large piece of data without copying it until a mutation occurs.

Requirements:

  • Create a private class called BufferStorage that holds an array of integers. This class will act as the shared reference.
  • Create a struct called CustomBuffer that holds a reference to an instance of BufferStorage.
  • Implement a method updateValue(at index: Int, to value: Int) inside CustomBuffer.
  • Inside updateValue, use isKnownUniquelyReferenced to check if the storage is shared. If it is, create a new copy of the BufferStorage before modifying the value.
  • Verify your implementation by creating two CustomBuffer instances, assigning one to the other, and ensuring that updating one does not affect the other.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.