skip to content

A Swift SettingsStore class saves to disk in didSet on its recentFiles array; why do three appends write three times while its initializer writes nothing?

level: seniorimportance: should knowfreq 35%

answer

  1. arrays are values
  2. read, modify, write back
  3. initialization skips observers
  4. batch on a local copy
  5. oldValue is not free

basics

~20 s

Mutating part of a value-typed property, such as an append or a nested field write, writes the whole property, so didSet runs once per mutation. Assignments in the type's own initializer skip observers, so nothing saves there.

solid answer

~50 s

`[String]` is a value type, so `store.recentFiles.append(name)` modifies the property in place and then counts as a **set** of `recentFiles`: `didSet` runs after every append, every element write, every change to a field of a struct-typed property, every `inout` pass, and even a same-value assignment. The initializer's assignments are an initialization context, where observers are not called, so the initial values are never saved. Fixes: batch changes on a local copy and assign once, call `save()` explicitly where a save is wanted, or debounce the writes. Two further traps: if `didSet` reads `oldValue`, Swift must fetch the old array before each mutation, so each element write copies the whole array (since Swift 5.3, a `didSet` that never mentions `oldValue`, with no `willSet`, lets the mutation happen in place); and if the property held a **class** instance, changing its fields would not call `didSet` at all.

code

swift · 33 lines
swift
struct Preferences {
    var fontSize = 14
    var showsHiddenFiles = false
}

final class SettingsStore {
    var saveCount = 0

    var recentFiles: [String] { didSet { save() } }
    var preferences: Preferences { didSet { save() } }

    init(recentFiles: [String], preferences: Preferences) {
        self.recentFiles = recentFiles      // no didSet here
        self.preferences = preferences      // no didSet here
    }

    func save() { saveCount += 1 }  // stands in for a disk write
}

let store = SettingsStore(recentFiles: [], preferences: Preferences())
print(store.saveCount)                      // 0
for name in ["a.txt", "b.txt", "c.txt"] {
    store.recentFiles.append(name)          // one save per append
}
store.preferences.fontSize = 16             // nested write: one save
store.preferences.fontSize = 16             // same value: still a save
print(store.saveCount)                      // 5

var batch = store.recentFiles               // batch on a local copy
batch.removeAll()
batch += ["d.txt", "e.txt"]
store.recentFiles = batch                   // one save for the batch
print(store.saveCount)                      // 6

go deeper

for a junior

Recall that arrays and structs are values, so changing part of one counts as setting the whole property.

for a middle

Explain the get, mutate, set-back sequence behind an append, and why observers stay silent during the type's own initializer.

for a senior

Diagnose the write storm, fix it by batching or debouncing, and spot the oldValue copy cost and the silent class-typed property trap in review.

for a principal

Set a team rule for side effects in observers: persistence, networking and analytics belong in explicit operations whose frequency is visible, not behind assignment syntax.

## The symptom A settings object persists itself from an observer: ```swift var recentFiles: [String] { didSet { save() } } ``` Opening three files calls `recentFiles.append(_:)` three times and writes the file three times, while creating the store, which assigns `recentFiles` in `init`, writes nothing. Both behaviours follow from two Swift rules: a mutation of a value-typed property is a set of the whole property, and observers are skipped during the type's own initialization. ## Why every mutation is a set `Array`, `Dictionary`, `String` and your own structs are **value types**. A property of value type has no inner object that can change independently; the property's value is the array. So `store.recentFiles.append("a.txt")` is conceptually: 1. get the current value of `recentFiles`; 2. run the mutating method `append(_:)` on it; 3. store the result back into `recentFiles`. Step 3 is a set, so `willSet` and `didSet` run. The same holds for every way of mutating part of the value: | Write | Calls `didSet` on the property? | |---|---| | `store.recentFiles.append("a.txt")` | Yes, once per call | | `store.recentFiles[0] = "z.txt"` | Yes | | `store.preferences.fontSize = 16` (struct-typed property) | Yes | | The same assignment repeated with an equal value | Yes, no comparison is made | | Passing `&store.recentFiles` to an `inout` parameter | Yes, on write-back when the function returns | | A mutating method that changes several fields in one call | Once, for that one call | | Assignments inside the class's own `init` | No | | `store.prefs.fontSize = 16` where `prefs` holds a class instance | No | The last row is the value-versus-reference edge. If the property holds a **class** instance, `store.prefs.fontSize = 16` changes the object the property points to; the property itself still holds the same reference, so nothing is set and `didSet` never runs. Turning `Preferences` into a class would stop the extra saves, and would also stop every save for changes made to its fields, silently. ## Why the initializer writes nothing Observers run only when a value is set outside an initialization context. While `SettingsStore.init` assigns `self.recentFiles`, it is establishing the first value, so `didSet` is not called. Usually that is what you want, since the values came from disk. If a save is required at creation, call `save()` explicitly at the end of the initializer. A subclass is different: when a subclass initializer assigns an inherited observed property after `super.init`, the superclass's observers do run. ## The hidden cost of oldValue Before Swift 5.3, Swift fetched the old value for every `didSet`, used or not. SE-0268 (implemented in Swift 5.3) changed two things: - a **simple** `didSet`, one whose body never refers to `oldValue`, skips fetching the old value; - if the observer is simple and there is **no `willSet`**, the mutation can happen **in place**. When `didSet` does read `oldValue`, Swift has to keep the previous array alive while the new one is built, so an element write in a loop copies the whole array each time. Over `n` elements that is roughly quadratic work, easy to miss in review. In a quick check with Swift 6.4, a loop writing 20,000 elements of an observed array was more than an order of magnitude slower, in both debug and optimized builds, when the observer read `oldValue`. ## Fixing the store 1. **Batch on a local copy.** Copy the array into a local `var`, make all changes, assign once: one `didSet`, one save. 2. **Make persistence explicit.** Replace the observer with a `save()` call at the end of each public operation, or a batch method of your own that suppresses saves until its closure finishes. 3. **Debounce.** Let `didSet` mark the store dirty and schedule one write a moment later, coalescing a burst of changes. 4. **Skip unchanged values only where it pays.** `guard oldValue != recentFiles else { return }` avoids same-value writes, but reading `oldValue` brings back the copy cost, so use it for small values, not large collections written in loops. 5. **Keep the property value-typed.** Converting to a class to silence observers trades too many saves for missing ones. ## What to say in review - An observer on a collection or struct property runs per mutation, not per logical operation. - Observers do not run in the type's own `init`; persistence that must happen at creation is explicit. - Reading `oldValue` in a `didSet` on a large value has a measurable cost; a simple `didSet` lets in-place mutation survive.

  • Would making Preferences a class stop the extra saves?
    It would stop them for the wrong reason. A property of class type holds a reference; changing the object's fields does not set the property, so didSet never runs and preference changes would no longer be saved at all. Keep it a struct and batch the writes instead.
  • Does adding guard oldValue != recentFiles to didSet fix the repeated writes?
    Only for same-value assignments. Each append really changes the array, so each still saves. And because the observer now reads oldValue, Swift must keep the previous array for every mutation, so in-place element writes become full copies. Batching or debouncing fixes the write count without that cost.
  • When does a superclass's didSet run during initialization?
    When a subclass initializer assigns the inherited property after calling super.init. Observers are skipped only while a type assigns its own properties in its own initializer; once the superclass is initialized, the subclass's assignment is an ordinary set.

  • Appending to an array property does not call its didSet; only reassigning it does.
  • Observers also fire for the assignments in the type's own initializer.
  • Reading oldValue in didSet costs nothing, whatever the property's type.
  • Changing a field of a class-typed property calls that property's didSet.
  • didSet skips the call when the new value equals the old one.