skip to content

In Swift, how do you give a large Matrix struct copy-on-write behaviour with a class box and `isKnownUniquelyReferenced(_:)`, and what breaks it?

level: seniorimportance: should knowfreq 45%

answer

  1. share storage until a write
  2. private final class box
  3. check uniqueness in every mutating path
  4. strong references only; debug && and ||

basics

~20 s

Keep the elements in a private class instance; in every mutating method call isKnownUniquelyReferenced(&storage) and, when it returns false, replace the box with a clone before writing. Copies share the box until one of them writes.

solid answer

~50 s

Store the elements in a private, usually `final`, class and hold it in a `var` property. Copying the `Matrix` then copies one reference. Each mutating method first calls `isKnownUniquelyReferenced(&storage)`: `true` means no other strong reference exists, so writing in place is invisible to anyone; `false` means another copy shares the box, so you assign `storage = storage.copy()` and then write. What breaks it: a non-mutating method that writes through the box (it compiles, because the reference is not being changed); a write path that skips the check; holding an extra strong reference such as a local `let` across the check, which forces a clone on every write; and, per the standard library's documentation, calling it on the right of `&&` or `||` in debug builds, where the left operand can keep a reference alive. It counts only strong references and is not a synchronization primitive.

code

swift · 31 lines
swift
final class MatrixStorage {
    let columns: Int
    let elements: UnsafeMutableBufferPointer<Double>
    init(rows: Int, columns: Int) {
        self.columns = columns
        elements = .allocate(capacity: rows * columns)
        elements.initialize(repeating: 0)
    }
    func copy() -> MatrixStorage {
        let clone = MatrixStorage(rows: elements.count / columns, columns: columns)
        _ = clone.elements.update(fromContentsOf: elements)
        return clone
    }
    deinit { elements.deallocate() }
}

struct Matrix {
    private var storage: MatrixStorage
    init(rows: Int, columns: Int) { storage = MatrixStorage(rows: rows, columns: columns) }
    func value(row: Int, column: Int) -> Double { storage.elements[row * storage.columns + column] }
    mutating func setValue(_ value: Double, row: Int, column: Int) {
        if !isKnownUniquelyReferenced(&storage) { storage = storage.copy() }
        storage.elements[row * storage.columns + column] = value
    }
}

var a = Matrix(rows: 2, columns: 2)
var b = a                          // one shared storage, no element copy
b.setValue(7, row: 0, column: 0)   // not unique: b clones, then writes
a.setValue(1, row: 1, column: 1)   // a is unique again: writes in place
print(a.value(row: 0, column: 0), b.value(row: 0, column: 0))   // 0.0 7.0

go deeper

for a junior

Recall the idea: copies share one storage object and the struct duplicates it only just before a write, if another copy still uses it.

for a middle

Explain the moving parts: a private class box held in a var, reads straight through, and isKnownUniquelyReferenced(&storage) followed by a clone in every mutating path.

for a senior

Show you can review an implementation: catch non-mutating writes through the box, unchecked setters, extra strong references, the debug && and || trap, and missing synchronization.

for a principal

Weigh hand-written copy-on-write against composing Array or using ManagedBuffer: every extra write path is a place value semantics can silently break.

## Why build copy-on-write yourself A struct gives callers value semantics, but copying a large struct copies all of its stored data. **Copy-on-write (COW)** keeps the semantics and drops the cost: copies share one storage buffer, and the buffer is duplicated only when a copy that shares it is about to be modified. The standard collections already work this way, and the simplest route is often to store your data in an `Array`, which the material on arrays covers. You write COW by hand when the storage is not an array — a manually allocated buffer, an object from a C library, several fields that must be cloned together — or when you do not want to expose array APIs. ## The pattern 1. **A private class owns the data.** Here `MatrixStorage` allocates an `UnsafeMutableBufferPointer<Double>`, can produce a deep `copy()`, and frees the buffer in `deinit`. It is `final` because nothing should subclass it. 2. **The struct holds it in a `private var`.** Copying a `Matrix` copies one reference and nothing else. 3. **Reads go straight through.** `value(row:column:)` reads the buffer without any check; reading shared storage is harmless. 4. **Every write checks first.** `setValue(_:row:column:)` is `mutating` and starts with `if !isKnownUniquelyReferenced(&storage) { storage = storage.copy() }`, then writes into storage it now owns alone. After `var b = a`, both matrices share one buffer. `b.setValue(...)` finds the storage shared, clones it and writes into the clone. The original `a` is then the only owner of the old buffer, so its next write happens in place. ## What `isKnownUniquelyReferenced(_:)` actually checks The standard library documents it as returning whether the object *is known to have a single strong reference*. The details you are expected to know: - It takes its argument **`inout`**, so the box must be a mutable `var` property; with a `let` property the compiler reports `cannot pass immutable value as inout argument: 'storage' is a 'let' constant`. The documentation calls the `inout` an implementation artifact — the function does not modify the reference. - It counts **strong references only**. Extra `weak` or `unowned` references do not make it return `false`, and passing a weak or unowned reference itself always yields `false`. - An overload takes an optional and returns `false` for `nil`. - It is **not thread-safe on its own**: if the instance is accessed from several threads at once it may still return `true`, so the documentation says to call it only from mutating methods with appropriate synchronization. ## Ways to break it - **A non-mutating write.** A `func fill(_:)` that is not `mutating` can still write through the reference, because it never changes `storage` itself. It compiles and leaks the write into every copy — the second example shows a copy printing the value written through the other. - **A write path without the check.** Every setter, subscript setter and mutating method must check; one forgotten path is enough. - **An extra strong reference.** Copying the box into a local `let` before the check makes the count two, so every write clones. - **Boolean expressions in debug builds.** The documentation warns that in `myStorage.shouldCopy || !isKnownUniquelyReferenced(&myStorage)`, the left operand may keep the instance referenced, so the type copies on every call. Evaluate the other condition into a local first, or put the uniqueness check on the left. - **Exposing the box.** If any API returns `storage`, an outside reference keeps it non-unique and can also mutate it directly. ## Testing that it really copies on write Copy-on-write bugs are silent: everything compiles and most tests pass. Two cheap checks catch them: 1. **Behavioural:** make a copy, write through one side, and assert that the other side still holds its old value — for every public mutating API, not only the first one you wrote. 2. **Counting clones:** in a test build, count calls to the storage's `copy()`; a loop of writes on a unique value should clone zero times, and a write after `var b = a` exactly once. A count that grows with every write points to an extra strong reference. ## Choosing the storage | Storage | Copy cost when shared | Effort | |---|---|---| | `[Double]` property in the struct | Array handles it | none — compose an existing COW type | | Private class box plus `isKnownUniquelyReferenced(_:)` | your `copy()` | every write path must check | | `ManagedBuffer` subclass | your copy routine | a `Header` plus raw element storage in one class instance | The Swift optimization guide recommends composing existing COW types first and shows the class-box variant as the alternative when array's extra API and checks get in the way.

  • Why does the standard library warn against calling `isKnownUniquelyReferenced(_:)` on the right-hand side of `||`?
    Its documentation says that in debug builds an instance in the left-hand side of `&&` or `||` may still be referenced while the right-hand side is evaluated, which inflates the count. `myStorage.shouldCopy || !isKnownUniquelyReferenced(&myStorage)` then copies on every call. Store the first condition in a local constant, or put the uniqueness check on the left.
  • Is `isKnownUniquelyReferenced(_:)` safe to call from several threads?
    Not by itself. The documentation says that if the instance is accessed by multiple threads simultaneously it may still return `true`, so you must call it only from mutating methods with appropriate synchronization; then `true` means one accessor or a race that is already undefined behaviour. Value types help here: each thread working on its own copy of the struct owns its own reference.
  • Why not just store the matrix elements in an `Array` instead?
    Often you should: an `Array` property already gives the struct copy-on-write, and the Swift optimization guide recommends composing existing COW types first. A hand-written box earns its keep when the storage is not an array, when several fields must be cloned as one unit, or when you want to avoid array's extra API and its run-time checks.

  • The struct's storage is copied as soon as the struct is assigned to another variable.
  • isKnownUniquelyReferenced(_:) also counts weak and unowned references.
  • Only mutating methods can change the class box, so the compiler enforces copy-on-write.
  • The box can be a let property because the box object itself never changes.
  • isKnownUniquelyReferenced(_:) makes copy-on-write thread-safe without any other synchronization.