How it works
A DocumentCreationContext carries information about a document that SwiftUI is about to create, handing it to your scene at the moment a new file is requested. You receive it inside a DocumentGroup's new-document closure, where it lets your initialization logic adapt to how and why the document was started rather than always producing an identical blank file. Reach for it when the same document type should open differently depending on its origin, so the context becomes the single place to read that intent and seed the model accordingly.
Receive the context from DocumentGroup's new-document closure
DocumentCreationContextis not something you construct yourself; SwiftUI builds it and passes it to the closure you supply when configuring aDocumentGroupfor new documents. That closure is the hook where the system reports that a fresh file is being made, mirroring theCreate Documentbutton action in the example that signals the same intent to start a new document.Read the context to branch your initialization
Inside the closure, inspect the
DocumentCreationContextvalue to decide how to populate the new document instead of returning a fixed default. This is the structure's whole job: turning one creation entry point into branching setup logic, the work the comment in the example points at where it notes thenewDocumentclosure receives aDocumentCreationContextdescribing the new file.Return a configured document model
After consulting the context, the closure produces and returns the document instance that backs the editor scene. The
DocumentCreationContextinfluences that returned value rather than the view tree itself, so state such as the example'snewDocscounter conceptually stands in for the per-creation bookkeeping you would update as each contextualized document is built.Keep the context scoped to creation only
A
DocumentCreationContextis meaningful only during the creation moment and is not retained as document state, which is why the view body inDocumentCreationContextDemonever references it directly. TheImage,Text, andButtonhere are ordinary scene chrome; the symbol lives upstream in the document-group plumbing that drives them.
Create Document button's newDocs += 1 action to set distinct values based on a condition, mirroring how reading the DocumentCreationContext would let the new-document closure seed different starting content per creation.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 DocumentCreationContextDemo: View {
@State private var newDocs = 0
var body: some View {
VStack(spacing: 16) {
Image(systemName: "doc.badge.plus")
.font(.system(size: 44))
.foregroundStyle(.tint)
Text("New Documents: \(newDocs)")
.font(.headline)
Button("Create Document") {
// In a DocumentGroup, the newDocument closure receives
// a DocumentCreationContext describing the new file.
newDocs += 1
}
.buttonStyle(.borderedProminent)
}
.padding()
}
}