Build An Undoable SwiftUI Editor With Value Snapshots
A small editor often starts with bindings that directly mutate a draft. Adding Undo later becomes awkward because the previous value has already disappeared by the time anyone thinks to save it.
Put user edits through one method instead. That method can capture the old value, register its inverse, and then publish the new value. For a small draft, a value snapshot makes the behavior easy to see.
Make the inverse use the same edit path
Here is an editor for a card with a title and a pinned state:
import Combine
import Foundation
struct CardDraft: Equatable, Sendable {
var title: String
var isPinned: Bool
}
@MainActor
final class CardEditor: ObservableObject {
@Published private(set) var draft: CardDraft
weak var undoManager: UndoManager?
init(draft: CardDraft) { self.draft = draft }
func replace(with next: CardDraft, actionName: String) {
guard next != draft else { return }
let previous = draft
undoManager?.registerUndo(withTarget: self) { target in
target.replace(with: previous, actionName: actionName)
}
undoManager?.setActionName(actionName)
draft = next
}
}
The registered operation calls replace again. While an undo is running, that call captures the state being removed and registers the inverse needed for redo. If the closure simply assigned draft = previous, Undo might appear to work once while Redo had nothing useful to replay.
Apple’s UndoManager documentation describes the manager and its main-actor isolation. The registration method supplies the target to the handler. Using that parameter avoids unnecessarily capturing the editor again in the closure.
The equality guard keeps a no-op assignment out of the history. The action name gives the system a meaningful command, such as “Undo Rename,” rather than an anonymous step.
Connect the scene’s manager
SwiftUI exposes an optional undo manager in the environment. Connect the manager belonging to the active editor scene, and update that connection when the scene’s environment changes. The weak property avoids making the model the lifetime owner of the scene’s manager.
Do not use one global manager for every open document. Undo in one window should not unexpectedly edit another window’s draft. When the document closes, clear that target’s actions as part of the editor lifecycle if the manager can outlive it.
The optional manager also makes the no-history case explicit: edits still work when no manager is supplied. In a preview or a deliberately non-undoable workflow, the model can operate without manufacturing a hidden manager of its own.
Choose what one action means
A “Pin Card” command is naturally one step. A slider gesture may emit dozens of intermediate values but represent one user decision. A text field may have editing behavior of its own, so registering every binding update can produce a second, conflicting history.
Choose the transaction boundary at the control or command layer. For a gesture, hold the initial snapshot, show intermediate UI changes, and commit one undoable transition when the gesture ends. For several related commands that should undo together, use an explicit undo group and close it on every path.
Do not leave a group open across an arbitrary network request. Another user action may arrive while it is suspended, and the group can accidentally absorb unrelated edits. Apple also notes that canUndo alone does not prove an open group is safe to undo.
Keep snapshots local to the draft
The example replaces the whole value. That is convenient because both fields belong to one small editor-owned draft. It is a poor default for a giant document or a shared live model receiving independent remote changes.
For larger models, register a focused inverse command: restore a deleted item at a particular stable ID, move a shape back to its previous position, or replace one field. Keep a memory budget for history, and avoid storing image buffers in every snapshot.
Undo also does not reverse a server write merely because the local UI changed. Apply undo to the local draft and let the normal save/sync design process the resulting state. If a product promises to reverse an already committed remote action, it needs an explicit server operation with its own failure behavior.
Test the full round trip
Create an UndoManager with groupsByEvent = false in the fixture and wrap the initial edit in beginUndoGrouping() and endUndoGrouping(). Then check edit → undo → redo. After another undo, make a different edit and verify that the old redo branch is gone.
Also register an unchanged snapshot and confirm it creates no undo action. These checks exercise behavior users can feel; checking only canUndo after one edit misses the broken-redo implementation.
September 2026 review: the Swift 6.4 executable passed inverse restoration, redo, redo invalidation after a new edit, and no-op suppression. Control grouping, keyboard commands, and multiple-window focus still need testing in the actual SwiftUI editor.
A useful undo history follows the user’s actions. Capturing a value is the easy part; deciding where an action begins and ends is what makes the editor feel predictable.