Save An Editable Document Without Truncating The Last Good Copy

An autosave can fail in two different ways. It can leave a partial file, or it can successfully save the wrong revision. Making the write atomic addresses the first problem. It does not decide which snapshot deserves to win.

For a small app-owned JSON document, we can handle both without inventing a document framework. Capture an immutable snapshot, give it a revision from the editor, and send it to one writer.

Encode before touching the destination

Do not truncate the current file before serialization has succeeded. Encode the snapshot first, then use the atomic writing option. Apple’s Data writing options describe writing an auxiliary file and replacing the original after that write completes.

That protects the single-file replacement boundary. It is not a transaction across a JSON file, a thumbnail, and a separate database row. It also does not validate the contents or provide an undo history.

Let one owner order the saves

This writer is for one process and one app-owned destination. The caller creates its storage directory and initializes savedRevision from the document it loaded:

import Foundation

struct EditorSnapshot: Codable, Sendable, Equatable {
    let revision: Int
    let text: String
}

actor SnapshotWriter {
    private let file: URL
    private var savedRevision: Int

    init(file: URL, savedRevision: Int) {
        self.file = file
        self.savedRevision = savedRevision
    }

    @discardableResult
    func save(_ snapshot: EditorSnapshot) throws -> Bool {
        guard snapshot.revision > savedRevision else { return false }
        let data = try JSONEncoder().encode(snapshot)
        try data.write(to: file, options: .atomic)
        savedRevision = snapshot.revision
        return true
    }
}

The editor increments its revision when it captures a changed snapshot. Revision 12 must always represent a later editor state than revision 11. Assigning numbers when network calls finish or when save tasks reach the writer would defeat that purpose.

Imagine snapshot 12 reaches the writer before snapshot 11. Both writes could be individually atomic, yet blindly accepting the second would restore older content. The revision guard rejects that obsolete save.

There is no await inside save. Once the actor starts this method, another save cannot interleave between the comparison and the disk write. The file operation is synchronous and belongs on this dedicated writer, not the main-actor editor. For large documents, a whole-document JSON buffer and a blocking file write may be the wrong architecture.

Advance saved state only after success

The assignment to savedRevision happens after the write returns successfully. If the disk operation throws, the same snapshot can be retried. Marking it saved before attempting the write would make that retry look like a duplicate.

The editor should follow the same rule. Keep the document dirty while a save is pending or failed. When revision 12 finishes saving, only mark the current editor clean if it is still revision 12. The user may already be editing revision 13.

A debounce timer changes when you ask for a save. It does not change these rules. Cancelling a scheduled autosave is fine; claiming a save completed because the timer fired is not.

Keep the scope small and explicit

All writes to this destination must go through the same owner. Creating two SnapshotWriter actors for the same URL gives each its own revision counter and removes the serialization guarantee. Another process or extension writing the file needs a coordination design beyond an actor in this process.

For a document managed by SwiftUI’s document system, use that system’s saving hooks. Our WritableDocument post covers snapshot-based document integration. Do not add a competing raw file writer behind a document framework that already owns the file.

For a package with several related files, choose a package-level replacement or transactional storage strategy. Applying .atomic to each child independently still permits a mix of generations after an interruption.

Test ordering and failure independently

A useful fixture saves revision 3, then attempts revisions 2 and 3 again. Read the file back and verify that it still contains the original revision 3 payload. A duplicate revision with different bytes should reveal a bug in the caller’s snapshot identity, not silently overwrite the file.

For the failure path, point the writer at a missing parent directory, confirm the write throws, create the directory, and retry the same revision. That catches the “marked saved too early” bug without relying on timing or filling a device’s disk.

September 2026 review: the Swift 6.4 executable passed failed-write retry, stale-revision rejection, duplicate-revision rejection, and JSON round-trip checks. These tests exercise application ordering and ordinary write errors; they are not a power-loss durability test.

A save indicator should mean something precise: a particular editor revision was successfully written. Atomic replacement and revision ordering each contribute a different part of that promise.