Building a document-based app with SwiftUI
At a glance
| Item | Summary |
|---|---|
| Purpose | Create, save, and open a JSON-encoded checklist document in one SwiftUI app target that builds for iPhone, iPad, and Mac. |
| App architecture | DocumentBasedApp declares a DocumentGroup whose makeDocument closure creates an @Observable ChecklistDocument. ChecklistView edits it through @Bindable, and each ChecklistRow receives a binding to one item plus the document for undo-aware edits. |
| Main patterns | An observable, reference-type document that owns the model value and every undoable mutation; element bindings handed from ForEach to rows. |
| Project style | One flat DocumentBasedApp/ source folder with one type per file, plus per-platform iOS/ and macOS/ folders that hold only Info.plist (and the macOS entitlements). |
| Execution model | Every document mutation, snapshot(contentType:), and apply(snapshot:previous:) is @MainActor. Reader and writer closures pass sending values; the source does not establish which executor runs them. No Task, queue, or lock appears. |
| State/event model | Observation (@Observable document, @Bindable view), SwiftUI bindings for items, @State/@FocusState for view-local UI state, and UndoManager read from the environment. |
| Key frameworks/packages | SwiftUI, UniformTypeIdentifiers, Foundation. The project declares no Swift package. |
Project structure
DocumentBasedApp.xcodeproj/ one application target, SUPPORTED_PLATFORMS iphoneos + macosx
DocumentBasedApp/
├── DocumentBasedApp.swift @main App: launch scene + DocumentGroup
├── ChecklistDocument.swift UTType, @Observable Document, undoable operations
├── Checklist.swift ChecklistItem / Checklist value types, starter content
├── ChecklistView.swift list, toolbar, delete/move handlers
├── ChecklistRow.swift checkbox + title field for one item
└── AccessoryView.swift decorative launch-screen overlay (iOS)
iOS/Info.plist document type, exported UTI, document browser
macOS/Info.plist, macOS.entitlements
DocumentBasedApp.entitlements
Structure observations
- The project has a single application target (
DocumentBasedApp.xcodeproj/project.pbxproj:155). It selects a differentInfo.plistand entitlements file per SDK through conditional build settings (DocumentBasedApp.xcodeproj/project.pbxproj:348,DocumentBasedApp.xcodeproj/project.pbxproj:361), so the platform split lives in configuration rather than in separate targets. - Persistence, the content type, and all editing operations sit in
ChecklistDocument.swift(DocumentBasedApp/ChecklistDocument.swift:12,DocumentBasedApp/ChecklistDocument.swift:65). The model fileChecklist.swifthas no SwiftUI import and contains only value types and twomutatinghelpers (DocumentBasedApp/Checklist.swift:8,DocumentBasedApp/Checklist.swift:37). - The custom document type
com.example.checklistis declared in code (DocumentBasedApp/ChecklistDocument.swift:13) and exported in bothInfo.plistfiles (iOS/Info.plist:79,macOS/Info.plist:51). - Platform differences are handled with
#if os(iOS)/#elseif os(macOS)inside the shared views (DocumentBasedApp/DocumentBasedApp.swift:14,DocumentBasedApp/ChecklistView.swift:37), not with separate view files.
Platform boundary
The DocC record lists iOS, iPadOS, Mac Catalyst, and macOS. The project sets SUPPORTED_PLATFORMS = "iphoneos iphonesimulator macosx" and SUPPORTS_MACCATALYST = NO (DocumentBasedApp.xcodeproj/project.pbxproj:384, DocumentBasedApp.xcodeproj/project.pbxproj:385), so the source builds a native macOS app rather than a Mac Catalyst one. It also sets iOS and macOS deployment targets of 27.0 (DocumentBasedApp.xcodeproj/project.pbxproj:364, DocumentBasedApp.xcodeproj/project.pbxproj:377). The README additionally mentions Vision Pro (README.md:7), which the target’s supported platforms do not list.
Overall architecture
flowchart LR
App["DocumentBasedApp"] --> Launch["DocumentGroupLaunchScene (iOS)"]
Launch --> Accessory["AccessoryView"]
App --> Group["DocumentGroup"]
Group -- "makeDocument" --> Doc["ChecklistDocument (@Observable)"]
Group --> View["ChecklistView"]
View --> Row["ChecklistRow"]
View --> Doc
Row --> Doc
Doc --> Model["Checklist / ChecklistItem"]
Doc --> IO["FileWrapper reader / writer (JSON)"]
Reference code
DocumentBasedApp/DocumentBasedApp.swift:12 — DocumentBasedApp
struct DocumentBasedApp: App {
var body: some Scene {
#if os(iOS) // DocumentGroupLaunchScene isn't available on macOS.
DocumentGroupLaunchScene("Checklist") {
NewDocumentButton("Start a Checklist")
} background: {
Image(.pinkJungle)
.resizable()
.scaledToFill()
} overlayAccessoryView: { _ in
AccessoryView()
}
#endif // os(iOS)
DocumentGroup { document in
ChecklistView(document: document)
} makeDocument: { configuration, context in
ChecklistDocument()
}
}
}Interpretation
Observed: the app entry contains no state of its own. It hands document creation to DocumentGroup through a makeDocument closure and receives the document instance in the content closure, which it passes straight to ChecklistView. The launch scene and its accessory overlay exist only in the iOS build.
Inference: because ChecklistDocument is a class conforming to Document rather than a FileDocument value, the view layer edits the same instance that SwiftUI later snapshots for saving, and the document can carry behavior (undo registration) alongside data.
Ownership and state
classDiagram
DocumentGroup *-- ChecklistDocument : makeDocument creates
ChecklistDocument *-- Checklist : var checklist
Checklist *-- ChecklistItem : items
ChecklistView o-- ChecklistDocument : @Bindable
ChecklistView *-- Selection : @State private selection
ChecklistRow o-- ChecklistDocument : let document
ChecklistRow o-- ChecklistItem : @Binding item
ChecklistRow *-- OldTitle : @State private oldTitle
Ownership evidence
DocumentBasedApp/ChecklistDocument.swift:16 — ChecklistDocument
@Observable
final class ChecklistDocument: Document {
var checklist: Checklist
// Define the document type this app can load.
/// - Tag: ContentType
static let readableContentTypes: [UTType] = [.checklistDocument]
init() {
checklist = .demoList
}
// ...
}DocumentBasedApp/ChecklistRow.swift:10 — ChecklistRow
struct ChecklistRow: View {
/// The document that owns this item. The row routes checkbox and title
/// edits through the document so each change registers its own undo action.
let document: ChecklistDocument
// ...
@Binding var item: ChecklistItem
@Environment(\.undoManager) private var undoManager
@FocusState private var isTitleFieldFocused: Bool
@State private var oldTitle = ""
// ...
}| Owner | Object or state | Relationship | Mutation authority |
|---|---|---|---|
DocumentGroup (SwiftUI) |
ChecklistDocument |
Created by the app’s makeDocument closure (DocumentBasedApp/DocumentBasedApp.swift:27); retention is framework-managed and not visible in source |
The document’s own @MainActor methods, plus direct binding writes |
ChecklistDocument |
checklist: Checklist |
Stored var, seeded with .demoList (DocumentBasedApp/ChecklistDocument.swift:26) and replaced by apply(snapshot:previous:) after a read |
Document methods; views also write through $document.checklist.items bindings |
ChecklistView |
document |
@Bindable var (DocumentBasedApp/ChecklistView.swift:12); receives, does not create |
Calls document methods; projects element bindings |
ChecklistView |
selection: Set<UUID> |
@State private var (DocumentBasedApp/ChecklistView.swift:22) |
List(selection:) and the delete button |
ChecklistRow |
item |
@Binding var supplied by ForEach (DocumentBasedApp/ChecklistView.swift:30) |
Checkbox via document.toggleItem; title via the TextField binding |
ChecklistRow |
oldTitle, isTitleFieldFocused |
@State private, @FocusState private |
The row, to remember the pre-edit title for undo |
AccessoryView |
size: CGSize |
@State private var, written from onGeometryChange (DocumentBasedApp/AccessoryView.swift:12, DocumentBasedApp/AccessoryView.swift:31) |
The view itself |
Observed: two write paths reach the model. Structural changes (add, delete, move, toggle) go through document methods that register undo actions. Title text is written directly through $item.title (DocumentBasedApp/ChecklistRow.swift:36), and the row registers undo afterwards on submit (DocumentBasedApp/ChecklistRow.swift:45).
Concurrency, scheduling, and thread safety
Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution; Sendable conformance alone does not prove thread-safe mutation.
| Concern | Source mechanism | Verified placement or handoff | Evidence |
|---|---|---|---|
| Main-actor isolation | @MainActor on apply(snapshot:previous:) and snapshot(contentType:) |
Loading a decoded checklist into checklist and copying it out for saving both run on the main actor |
DocumentBasedApp/ChecklistDocument.swift:42, DocumentBasedApp/ChecklistDocument.swift:58 |
| Main-actor isolation | @MainActor on every editing method in the extension |
toggleItem, addItem, deleteItem, deleteItems, replaceItems, delete, moveItemsAt, and registerUndoTitleChange mutate the document on the main actor |
DocumentBasedApp/ChecklistDocument.swift:71, DocumentBasedApp/ChecklistDocument.swift:85, DocumentBasedApp/ChecklistDocument.swift:172 |
| Value handoff | sending on reader/writer configurations, the snapshot return, and apply parameters |
snapshot returns a copy of the Checklist value (“Make a copy.”), so the encoder works on a value, not on the live document |
DocumentBasedApp/ChecklistDocument.swift:31, DocumentBasedApp/ChecklistDocument.swift:49, DocumentBasedApp/ChecklistDocument.swift:60 |
| Task or worker execution | FileWrapperDocumentReader / FileWrapperDocumentWriter closures |
The closures decode and encode JSON. They are not marked @MainActor, but the source does not establish which executor SwiftUI uses to call them. |
DocumentBasedApp/ChecklistDocument.swift:32, DocumentBasedApp/ChecklistDocument.swift:50 |
| Shared-state safety | None beyond main-actor isolation | No lock, queue, or actor protects checklist; the protection is the @MainActor annotation on every method that writes it outside binding writes from SwiftUI views |
DocumentBasedApp/ChecklistDocument.swift:19 |
| Compiler mode | SWIFT_VERSION = 6.0 |
The app target builds in Swift 6 language mode | DocumentBasedApp.xcodeproj/project.pbxproj:387 |
Reference code
DocumentBasedApp/ChecklistDocument.swift:31 — reader, apply, writer, snapshot
func reader(configuration: sending ReadConfiguration) -> sending FileWrapperDocumentReader<Checklist> {
FileWrapperDocumentReader(configuration) { fileWrapper in
guard let data = fileWrapper.regularFileContents else {
throw CocoaError(.fileReadCorruptFile)
}
return try JSONDecoder().decode(Checklist.self, from: data)
}
}
/// Applies a checklist loaded from disk to the document.
/// - Tag: Apply
@MainActor
func apply(snapshot: sending Checklist, previous: sending Checklist?) async throws {
checklist = snapshot
}
/// Encodes a checklist snapshot and writes it to a file.
/// - Tag: DocumentWriter
func writer(configuration: sending WriteConfiguration) -> sending FileWrapperDocumentWriter<Checklist> {
FileWrapperDocumentWriter(configuration) { snapshot, _ in
let data = try JSONEncoder().encode(snapshot)
return FileWrapper(regularFileWithContents: data)
}
}
/// Captures the document's current state for saving.
/// - Tag: Snapshot
@MainActor
func snapshot(contentType: UTType) async throws -> sending Checklist {
checklist // Make a copy.
}Interpretation: the document protocol splits I/O into four steps. Decoding produces a Checklist value that apply installs on the main actor; saving takes a main-actor snapshot copy that the writer encodes. Because Checklist is a struct, the snapshot is independent of later edits. Not established by source: whether the reader and writer closures run off the main actor.
State propagation, frameworks, and dependencies
Evidence limit: an import proves a source-level compilation dependency at the cited line; it does not prove runtime use, architectural adoption, or whether a Swift package is a direct application dependency.
| Category | Mechanism or module | Verified role | Evidence |
|---|---|---|---|
| State propagation | @Observable document read through @Bindable |
ChecklistView re-renders from document changes and projects $document.checklist.items |
DocumentBasedApp/ChecklistDocument.swift:16, DocumentBasedApp/ChecklistView.swift:12 |
| State propagation | ForEach($document.checklist.items) { $item in ... } |
Each row gets a binding to its own element; the source comment says ForEach manages that binding’s lifetime during deletes |
DocumentBasedApp/ChecklistView.swift:30 |
| State propagation | @Environment(\.undoManager) |
Both the list view and each row read the scene’s undo manager and pass it into document methods | DocumentBasedApp/ChecklistView.swift:15, DocumentBasedApp/ChecklistRow.swift:23 |
| State propagation | @Environment(\.editMode) (iOS) |
Disables the add button while editing | DocumentBasedApp/ChecklistView.swift:18, DocumentBasedApp/ChecklistView.swift:40 |
| Persistence | JSONDecoder / JSONEncoder over FileWrapper |
Checklist and ChecklistItem are Codable |
DocumentBasedApp/Checklist.swift:11, DocumentBasedApp/ChecklistDocument.swift:36 |
| Framework import | SwiftUI, UniformTypeIdentifiers |
Document protocol, scenes, views; UTType(exportedAs:) |
DocumentBasedApp/ChecklistDocument.swift:8, DocumentBasedApp/ChecklistDocument.swift:9 |
| Framework import | Foundation |
Model value types only | DocumentBasedApp/Checklist.swift:8 |
| Package declaration | None | The project file declares no Swift package reference | DocumentBasedApp.xcodeproj/project.pbxproj:155 |
No Combine import or publisher appears in the source.
Class and protocol design
classDiagram
class Document {
<<protocol>>
}
ChecklistDocument ..|> Document
ChecklistDocument *-- Checklist
Checklist *-- ChecklistItem
ChecklistView --> ChecklistDocument : calls operations
ChecklistRow --> ChecklistDocument : toggleItem, registerUndoTitleChange
Reference code
DocumentBasedApp/Checklist.swift:11 — model value types
struct ChecklistItem: Identifiable, Codable, Equatable {
var id = UUID()
var isChecked = false
var title: String
}
struct Checklist: Identifiable, Codable {
var id = UUID()
var items: [ChecklistItem]
}| Type | Responsibility | Depends on |
|---|---|---|
DocumentBasedApp |
Scene composition: launch scene (iOS) and DocumentGroup |
ChecklistDocument, ChecklistView, AccessoryView |
ChecklistDocument |
Holds the checklist, reads/writes files, performs undoable edits | Checklist, UndoManager, UTType |
Checklist, ChecklistItem |
Codable value model with starter content and addItem helpers |
Foundation |
ChecklistView |
List, selection, toolbar, delete/move handlers | ChecklistDocument, ChecklistRow |
ChecklistRow |
One item’s checkbox and editable title | ChecklistDocument, Binding<ChecklistItem> |
AccessoryView |
Decorative launch overlay that hides in compact width | horizontalSizeClass |
Observed: the sample declares no protocol of its own. ChecklistDocument is final and conforms to SwiftUI’s Document; the model types conform to Identifiable, Codable, and (for items) Equatable, which registerUndoTitleChange relies on through firstIndex(of:) (DocumentBasedApp/ChecklistDocument.swift:174).
Access control
| Symbol | Access | Verified effect | Likely rationale |
|---|---|---|---|
ChecklistDocument (DocumentBasedApp/ChecklistDocument.swift:17) |
final class, implicit internal |
Cannot be subclassed; visible module-wide | Inference: the document’s I/O and undo behavior are not meant to be overridden. |
ChecklistDocument.checklist (DocumentBasedApp/ChecklistDocument.swift:19) |
implicit internal var |
Views can write it, which ForEach($document.checklist.items) requires |
Inference: binding-based editing needs a settable property, so mutation is not restricted to document methods. |
ChecklistView.selection (DocumentBasedApp/ChecklistView.swift:22) |
private |
Only ChecklistView reads or writes selection |
Inference: selection is view state, not document state, so it is not saved. |
ChecklistRow.undoManager, isTitleFieldFocused, oldTitle (DocumentBasedApp/ChecklistRow.swift:23) |
private |
Row-local editing state | Inference: keeps per-row edit bookkeeping out of the document. |
AccessoryView.horizontal, size (DocumentBasedApp/AccessoryView.swift:11) |
private |
Layout-only state | Inference: purely presentational. |
Reference code
DocumentBasedApp/ChecklistView.swift:10 — view-private selection
struct ChecklistView: View {
/// The document that the app displays.
@Bindable var document: ChecklistDocument
// ...
/// The internal selection state.
@State private var selection = Set<UUID>()
// ...
}All types are in one module and none is public or open; undecorated declarations are Swift’s implicit internal.
Logic ownership and placement
| Logic | Owning type or file | Placement rationale |
|---|---|---|
| Content type and file format | ChecklistDocument (UTType.checklistDocument, reader, writer) |
Format knowledge stays with the document type that SwiftUI asks to read and write. |
| Starter content | Checklist.demoList (DocumentBasedApp/Checklist.swift:32) |
New documents start from a static value assigned in ChecklistDocument.init(). |
| Undoable edits | ChecklistDocument extension (DocumentBasedApp/ChecklistDocument.swift:65) |
Each operation mutates checklist and registers its inverse with the passed UndoManager. |
| Selection-based delete (macOS toolbar) | ChecklistView.deleteButton → deleteItems(withIDs:) |
The view owns selection; the document translates IDs to offsets (DocumentBasedApp/ChecklistDocument.swift:112). |
| Title-edit undo | ChecklistRow remembers oldTitle on focus; document registers undo on submit |
The text field writes live, so the row captures the before-value and the document records the change after it happens. |
| Platform toolbar | ChecklistView.toolbar with #if os(iOS) / #elseif os(macOS) |
iOS uses EditButton; macOS adds a delete button driven by selection (DocumentBasedApp/ChecklistView.swift:37). |
Design patterns
| Pattern | Source evidence | Purpose or tradeoff |
|---|---|---|
| Observable state owner | @Observable final class ChecklistDocument holds checklist and exposes @MainActor mutation methods (DocumentBasedApp/ChecklistDocument.swift:16, DocumentBasedApp/ChecklistDocument.swift:71) |
One reference-type owner per open document; views observe it and call its operations. The property stays writable for bindings, so the owner is the main, not the exclusive, mutation path. |
| Binding-based state propagation | ForEach($document.checklist.items) { $item in ChecklistRow(document: document, item: $item) } and @Binding var item (DocumentBasedApp/ChecklistView.swift:30, DocumentBasedApp/ChecklistRow.swift:21) |
Rows edit their own element without looking it up by ID; the source comment ties this to safe deletes. |
Observed but not labeled as a pattern: every undo registration re-invokes a document method that itself registers the inverse, which makes redo work without extra code (“Because it calls itself, this is redoable, as well.” at DocumentBasedApp/ChecklistDocument.swift:77). These are closures registered with UndoManager, not Command objects.
Main application flow
sequenceDiagram
actor User
participant View as ChecklistView
participant Doc as ChecklistDocument
participant Undo as UndoManager
User->>View: tap delete (macOS toolbar)
View->>Doc: deleteItems(withIDs:undoManager:)
Doc->>Doc: delete(offsets:undoManager:)
Doc->>Undo: registerUndo { replaceItems(oldItems) }
View->>View: selection.removeAll()
User->>Undo: Undo
Undo->>Doc: replaceItems(with: oldItems)
Doc->>Undo: registerUndo { replaceItems(newer items) }
Reference code
DocumentBasedApp/ChecklistView.swift:71 — delete button
var deleteButton: some View {
Button(action: {
withAnimation {
document.deleteItems(withIDs: Array(selection), undoManager: undoManager)
}
selection.removeAll()
}) {
Image(systemName: "trash")
}
// ...
}DocumentBasedApp/ChecklistDocument.swift:140 — delete and its undo registration
func delete(offsets: IndexSet, undoManager: UndoManager? = nil) {
let oldItems = checklist.items
withAnimation {
checklist.items.remove(atOffsets: offsets)
}
undoManager?.registerUndo(withTarget: self) { doc in
// Reuse `replaceItems`, which supports both undo and redo.
doc.replaceItems(with: oldItems, undoManager: undoManager)
}
}DocumentBasedApp/ChecklistDocument.swift:125 — replaceItems re-registers its inverse
func replaceItems(with newItems: [ChecklistItem], undoManager: UndoManager? = nil, animation: Animation? = .default) {
let oldItems = checklist.items
withAnimation(animation) {
checklist.items = newItems
}
undoManager?.registerUndo(withTarget: self) { doc in
// Because it calls itself, this is redoable, as well.
doc.replaceItems(with: oldItems, undoManager: undoManager, animation: animation)
}
}Observed: each registerUndo(withTarget:) closure is a callback that UndoManager invokes later, not at registration time. Delete, move, and the redo side of title edits all funnel into replaceItems, which swaps the whole item array and registers the reverse swap. The view never touches the undo stack directly; it only forwards the environment’s UndoManager.
Naming conventions
- Types: domain nouns with a role suffix for SwiftUI roles:
ChecklistDocument(document),ChecklistViewandChecklistRow(views),AccessoryView; plain nouns for values (Checklist,ChecklistItem). The app type is named after the project (DocumentBasedApp). - Protocols: none declared locally.
- Methods: imperative verbs that name the edit (
toggleItem,addItem,deleteItem,deleteItems(withIDs:),replaceItems(with:),moveItemsAt(offsets:toOffset:));registerUndoTitleChange(for:oldTitle:undoManager:)names a bookkeeping step rather than an edit. View handlers useon…(onDelete,onMove). Document protocol hooks use framework names (reader,writer,snapshot,apply). Booleans useis…(isChecked,isTitleFieldFocused). - Files and extensions: one primary type per file, named after it;
ChecklistDocument.swiftalso holds theUTTypeextension.// MARK:sections group the document operations by edit kind.
Architecture takeaways
- A reference-type
Documentlets the document own both data and behavior: the same instance supplies a value snapshot for saving and implements every undoable edit. - Saving works on a copied value (
snapshotreturns theCheckliststruct), so encoding never reads the live, main-actor document. - Undo is centralized: views pass the environment
UndoManagerinto document methods, and self-registering inverses give redo for free. - Binding writes and method calls are both valid mutation paths. The sample uses methods for structural edits and a binding plus after-the-fact undo registration for free-text edits.
- Platform variation is kept to conditional build settings and
#if osblocks inside shared files.
Source map
| Source file | Relevant symbols |
|---|---|
DocumentBasedApp/DocumentBasedApp.swift |
DocumentBasedApp, DocumentGroupLaunchScene, DocumentGroup |
DocumentBasedApp/ChecklistDocument.swift |
UTType.checklistDocument, ChecklistDocument, reader, apply, writer, snapshot, toggleItem, addItem, delete, replaceItems, moveItemsAt, registerUndoTitleChange |
DocumentBasedApp/Checklist.swift |
ChecklistItem, Checklist, demoList, addItem |
DocumentBasedApp/ChecklistView.swift |
ChecklistView, selection, addButton, deleteButton, onDelete, onMove |
DocumentBasedApp/ChecklistRow.swift |
ChecklistRow, item, oldTitle |
DocumentBasedApp/AccessoryView.swift |
AccessoryView |
iOS/Info.plist |
CFBundleDocumentTypes, UTExportedTypeDeclarations, UISupportsDocumentBrowser |
macOS/Info.plist |
CFBundleDocumentTypes, UTExportedTypeDeclarations |
DocumentBasedApp.xcodeproj/project.pbxproj |
Target, per-SDK Info.plist/entitlements, SUPPORTED_PLATFORMS, SUPPORTS_MACCATALYST, SWIFT_VERSION |
README.md |
Supported devices statement |