Contents

Document

A document that supports both reading and writing.

Declaration

protocol Document : ReadableDocument, WritableDocument

Overview

Document is a convenience protocol that combines ReadableDocument and WritableDocument. Conform to it when your document can both open and save files:

@Observable
final class TextDocument: Document {
    static let readableContentTypes = [UTType.plainText]

    var text: String = ""

    func reader(configuration: sending ReadConfiguration) -> sending FileWrapperDocumentReader<String> {
        FileWrapperDocumentReader(configuration) { fileWrapper in
            guard let data =
                fileWrapper.regularFileContents else {
                throw CocoaError(.fileReadCorruptFile)
            }
            return String(decoding: data, as: UTF8.self)
        }
    }

    func writer(configuration: sending WriteConfiguration) -> sending FileWrapperDocumentWriter<String> {
        FileWrapperDocumentWriter(configuration) { snapshot, _ in
            FileWrapper(
                regularFileWithContents: Data(snapshot.utf8)
            )
        }
    }

    @MainActor
    func snapshot(contentType: UTType) async throws -> sending String { text }

    @MainActor
    func apply(snapshot: sending String, previous: sending String?) async throws {
        text = snapshot
    }
}

Use DocumentGroup as your app’s first scene to opt into the document infrastructure (autosaving, file coordination, undo management, conflict resolution):

@main
struct MyApp: App {
    var body: some Scene {
        DocumentGroup { document in
            TextEditorView(document: document)
        } makeDocument: { configuration, context in
            TextDocument()
        }
    }
}

For a read-only document, conform only to ReadableDocument.

The document can be @MainActor or nonisolated, Sendable or not — use whichever works best for the app.

See Also

Storing document data in a reference type instance