Keep Built-In Presets Out Of Your SwiftData Store

A timer app ships with Focus and Break presets. On first launch, it finds an empty SwiftData store and inserts both. Another device does the same before its existing data arrives from iCloud. Now the user has two Focus presets, which is an ambitious interpretation of productivity.

The useful distinction is ownership: the app owns the preset catalog; the user owns their choices about it. A new installation can display the catalog without inserting a single model. SwiftData only needs a record when the user chooses something.

We’ll build that separation, including what happens when a later app release changes a default. We’ll also expose disagreeing records instead of quietly picking one. This is a catalog and persistence design, not a CloudKit conflict-resolution engine.

An empty local store cannot answer a cloud question

This Stack Overflow question about duplicate prepopulation still has no answers as of October 27, 2026. A related question about unique properties does have an answer. The recurring problem is that different devices can each create a record for the same logical thing.

Apple’s current SwiftData synchronization documentation still excludes unique constraints from its CloudKit-backed schema support. A stable presetID helps us recognize matching records; it does not make @Attribute(.unique) a cloud-wide lock.

Fatbobman’s discussion of SwiftData and asynchronous cloud mirroring is useful background here. The addition in this article is an explicit catalog-plus-choice implementation, with catalog-update and persistence tests. We remove the need to seed shared defaults, while keeping the remaining synchronization problem visible.

The example targets iOS 17 / macOS 14, compiled with Swift 6.4.2 and Xcode 27.2 RC. The nonisolated type annotations keep the plain value types independent of a project’s default actor isolation. Paste the Swift blocks below into one file in order, or use the complete verification sample. The download includes a macOS runner and an iOS Simulator harness, not a finished timer UI. It supplies the read model; your editor owns writes and reconciliation.

Give the catalog stable identities

Start with ordinary values. These are bundled with the app, so they don’t need to be @Model objects.

import Foundation
import SwiftData

nonisolated struct TimerPreset: Equatable, Sendable {
    let id: String
    let title: String
    let defaultMinutes: Int
    let isRetired: Bool
}

nonisolated enum PresetCatalog {
    static let current = [
        TimerPreset(id: "focus", title: "Focus",
                    defaultMinutes: 25, isRetired: false),
        TimerPreset(id: "break", title: "Break",
                    defaultMinutes: 5, isRetired: false)
    ]
}

nonisolated enum PresetChoice: Hashable, Sendable {
    case useDefault
    case minutes(Int)
}

nonisolated struct ChoiceSnapshot: Equatable, Sendable {
    let recordID: UUID
    let presetID: String
    let choice: PresetChoice
}

nonisolated enum PresetError: Error {
    case invalidMinutes
    case invalidCatalog
    case duplicateRecordID
    case unsupportedStoredChoice(String)
}

nonisolated func validate(_ choice: PresetChoice) throws {
    if case .minutes(let value) = choice,
       !(1...180).contains(value) {
        throw PresetError.invalidMinutes
    }
}

The IDs are domain keys, not localized titles or UUIDs generated on launch. Keep focus when its title changes. Don’t recycle that ID for a different feature later. A bundled JSON catalog can use the same approach; the tiny array keeps the example readable.

Our timer accepts whole minutes from 1 through 180. That is an app policy, not a SwiftData restriction.

An explicit .minutes(25) and .useDefault may both show 25 today. They express different intentions. If the next catalog changes Focus to 30, the explicit choice stays 25; the default-following choice becomes 30.

Stored choiceToday’s default: 25Later default: 30
No record2530
.useDefault2530
.minutes(25)2525

Reset means “follow the current default,” not “copy today’s default into a permanent override.”

Persist the choice, not another copy of the preset

Store a small discriminator and optional payload. Reading an unknown discriminator must fail visibly rather than silently turning the user’s setting into a default.

@Model final class StoredPresetChoice {
    var recordID: UUID = UUID()
    var presetID: String = ""
    var kind: String = "default"
    var minutes: Int?

    init(presetID: String, choice: PresetChoice) throws {
        try validate(choice)
        self.presetID = presetID
        switch choice {
        case .useDefault:
            self.kind = "default"
            self.minutes = nil
        case .minutes(let value):
            self.kind = "minutes"
            self.minutes = value
        }
    }

    func snapshot() throws -> ChoiceSnapshot {
        let choice: PresetChoice
        switch (kind, minutes) {
        case ("default", nil):
            choice = .useDefault
        case ("minutes", .some(let value)):
            choice = .minutes(value)
        default:
            throw PresetError.unsupportedStoredChoice(kind)
        }
        try validate(choice)
        return ChoiceSnapshot(recordID: recordID,
                              presetID: presetID, choice: choice)
    }
}

recordID identifies a stored choice. presetID identifies the built-in preset it concerns. Several physical records can refer to focus; this model deliberately does not pretend otherwise.

The strings default and minutes are persistent format values. Renaming an enum case in source should not accidentally rename the data on disk. Adding a new choice requires an explicit compatibility policy. This reader rejects unsupported or malformed rows and leaves them stored; an app should show a load error, not catch it and render an empty store.

Build the displayed catalog without mutating the store

A projection turns the supplied catalog and current choice snapshots into display values. It is a pure read: no inserts, deletes, saves, or timestamp guesses.

nonisolated enum EffectiveMinutes: Equatable, Sendable {
    case value(Int)
    case conflict(Set<PresetChoice>)
}

nonisolated struct EffectivePreset: Equatable, Sendable {
    let preset: TimerPreset
    let minutes: EffectiveMinutes
    let recordIDs: Set<UUID>
}

nonisolated struct PresetProjection: Equatable, Sendable {
    let rows: [EffectivePreset]
    let unknownPresetChoices: [ChoiceSnapshot]
}

nonisolated func projectPresets(
    catalog: [TimerPreset], choices: [ChoiceSnapshot]
) throws -> PresetProjection {
    let catalogIDs = Set(catalog.map(\.id))
    guard catalogIDs.count == catalog.count,
          catalog.allSatisfy({ !$0.id.isEmpty &&
                              (1...180).contains($0.defaultMinutes) }) else {
        throw PresetError.invalidCatalog
    }
    guard Set(choices.map(\.recordID)).count == choices.count else {
        throw PresetError.duplicateRecordID
    }
    for row in choices { try validate(row.choice) }

    let grouped = Dictionary(grouping: choices, by: \.presetID)
    let rows = catalog.map { preset in
        let records = grouped[preset.id] ?? []
        let intentions = Set(records.map(\.choice))
        let result: EffectiveMinutes
        if intentions.count > 1 {
            result = .conflict(intentions)
        } else {
            switch intentions.first ?? .useDefault {
            case .useDefault:
                result = .value(preset.defaultMinutes)
            case .minutes(let value):
                result = .value(value)
            }
        }
        return EffectivePreset(
            preset: preset, minutes: result,
            recordIDs: Set(records.map(\.recordID))
        )
    }
    return PresetProjection(
        rows: rows,
        unknownPresetChoices: choices.filter {
            !catalogIDs.contains($0.presetID)
        }
    )
}

The catalog determines display order. A set makes equal intentions count once, so two distinct records containing .minutes(20) display one value while both record IDs remain available. One displayed row does not mean one stored record. Nothing was deduplicated in the database.

A .useDefault record and a .minutes(25) record are a conflict even when the current default is 25. Choosing one because they happen to look equal would lose the difference that matters during an upgrade. Treat .conflict as an unavailable timer value and show a “Review choices” state; don’t silently start a timer with whichever row fetched first. The set has no presentation order, so sort any choices shown to a person.

The input is a current record snapshot, not an append-only event log. Two entries with the same recordID are rejected. This detects disagreements between distinct records present in the snapshot; it cannot recover an edit already overwritten on a single record by a synchronization layer.

Keep retired entries in the catalog when existing references still need a name and default. isRetired lets the UI hide them from the new-timer picker while retaining a history or settings view. Choices for IDs this app doesn’t know are returned separately. They may belong to a newer catalog on another device; don’t delete them merely because this binary can’t display them.

Connect the read to SwiftData

Use a normal fetch for this small fixed catalog. The helper takes a store URL so the verification sample can use disposable files. Its parent directory must already exist.

@MainActor func makeLocalPresetContainer(at url: URL) throws
    -> ModelContainer {
    let schema = Schema([StoredPresetChoice.self])
    let configuration = ModelConfiguration(
        schema: schema, url: url, cloudKitDatabase: .none
    )
    return try ModelContainer(for: schema,
                              configurations: configuration)
}

@MainActor func readPresets(
    catalog: [TimerPreset], context: ModelContext
) throws -> PresetProjection {
    let records = try context.fetch(FetchDescriptor<StoredPresetChoice>())
    return try projectPresets(catalog: catalog,
                              choices: records.map { try $0.snapshot() })
}

CloudKit is explicitly disabled in the runnable example. That keeps its proof about local persistence and catalog ownership. Enabling sync later requires your own container, entitlements, schema deployment and multi-device tests; replacing .none is not the complete job.

On launch, read the choices and render the projection. Do not insert StoredPresetChoice objects just to fill empty slots. For SwiftUI, @Query can supply the records and you can project their snapshots when its inputs change. A direct fetch is a point-in-time read, not an observation subscription.

On an explicit user action, create a choice if there is no existing record, or update the record your editor owns, then handle save() errors. Do not append a new record on every edit and expect this projection to resolve the history. In a local-only editor, reset can update that owned row to kind = "default" and minutes = nil. If several records already exist, that is a separate reconciliation decision; this example intentionally supplies no destructive cleanup helper.

A stored reset is an explicit intention. It is not a timestamped command that automatically defeats older or later cloud records. With sync enabled, a delayed override may turn a previously resolved slot into a conflict. Missing local choices mean “show this version’s default for now,” not “the cloud has no choices.” Two app versions may also show different defaults for .useDefault until their bundled catalogs match.

Test the upgrade, not just the first launch

The download extracts these exact declarations and exercises the following boundaries:

  • Two empty stores each display the catalog while retaining zero stored choices.
  • An explicit 25-minute choice stays 25 after the default changes to 30; a reset follows 30.
  • Equivalent duplicate records remain on disk. Different intentions remain conflicts regardless of input order.
  • Retired presets and unknown IDs retain their user choices.
  • Invalid durations, malformed payloads, unsupported kinds, duplicate catalog IDs and repeated record IDs are rejected.
  • Reads leave ModelContext.hasChanges false and preserve the physical row count.

The persistence checks reopen disk stores across separate processes, including after writing an unsupported future choice. The same core checks also run in an iOS 27 Simulator app, built with an iOS 17 deployment target. Both ordinary and MainActor default-isolation builds are checked. These are local-store tests, not evidence of CloudKit convergence, older-OS runtime behavior or a finished editing UI.

For an existing app, changing ownership is a migration. Don’t delete old seeded rows just because their value matches a bundled default: the user may have explicitly chosen that value. Preserve ambiguous values as explicit choices, map old identities deliberately, and test the migration against real old-store fixtures. Our intermediate-schema migration article covers the mechanics of a staged SwiftData migration.

The payoff is a smaller responsibility for persistence. The app ships its built-in presets once. Stored records describe what the user chose, and a default update can respect that choice without creating another catalog in their database.