How it works
DocumentReader is a protocol that describes types capable of materializing a document's contents from a configuration that the system supplies. When SwiftUI's document infrastructure opens a file on behalf of your app, it hands a conforming reader the raw configuration — the file's data, its content type, and related metadata — and the reader is responsible for decoding that into the model your views display. Adopt DocumentReader when you want to separate the mechanics of reading and interpreting file contents from the SwiftUI scene that presents them, so that the same loading logic can be reused across document windows and content views.
Conform a type to DocumentReader
DocumentReader is the entry point for turning a stored file into in-memory contents. A conforming type accepts the configuration the system provides and exposes the decoded value your interface binds to — here the loaded text drives the
contentsstate thatDocumentReaderDemoshows in itsText(contents).Read from the supplied configuration
The reader's job is to consume the configuration that accompanies an open request — the file's data and its content type — rather than reaching for the file system directly. That decoded result is what populates a view's source of truth, such as the
@State private var contentsstring that begins as the document's existing body.Bind the decoded contents into the view
Once DocumentReader has produced a value, drive your SwiftUI hierarchy from it. In the example the decoded text flows into
Text(contents)inside aScrollView, and aLabel("Notes.txt", systemImage: "doc.text")names the document the reader loaded — the reader supplies the model, the view only presents it.Let edits write back through the same contents
Because the reader's output is held in observable state, mutating it updates the presentation immediately and gives a writer a consistent value to persist. The
Button("Append Line")appends tocontents, demonstrating how downstream edits build on top of whatever the reader originally decoded.
@State private var contents to a multi-paragraph string to see how the contents a DocumentReader hands off flow directly into Text(contents) and scroll within the ScrollView.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct DocumentReaderDemo: View {
@State private var contents = "Welcome to Chapter 1.\nThe quick brown fox jumps over the lazy dog."
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Label("Notes.txt", systemImage: "doc.text")
.font(.headline)
Divider()
ScrollView {
Text(contents)
.frame(maxWidth: .infinity, alignment: .leading)
}
Button("Append Line") {
contents += "\nAdded a new line."
}
.buttonStyle(.borderedProminent)
}
.padding()
}
}