How it works
DocumentCreationSource is a structure that identifies where a newly created document originated — whether the system built it from a blank template, from content on the pasteboard, or by importing an existing file. SwiftUI passes a value of this type into the document-creation closures of a document-based scene, so your app can tailor the initial state of a document to the action the user took. Reach for it when a single document type should start out differently depending on how the user asked for it, rather than always opening to an identical empty state.
Receive the source in the document-creation closure
A
DocumentCreationSourcevalue is handed to you by the scene at the moment a new document is requested; you do not construct one yourself. Branch on it to decide how to populate the model — the demo mirrors this by tracking the chosen origin in thesourcestate property and reflecting it in theText(source)readout.Distinguish a blank document
When the user starts fresh, the source identifies a blank or template-based creation, and you initialize the document to its empty or default contents. The
"Blank Template"option in thePickerstands in for this default path, which is the valuesourceholds when the view first appears.Distinguish a paste-driven document
When creation is driven by the pasteboard, the source signals that the document should be seeded with clipboard contents, letting you decode and insert that data as the document's starting point. The
"From Clipboard"tag in thePickerrepresents this branch of the decision.Distinguish an imported document
When the document originates from an external file, the source indicates an import, so you can read the incoming file and convert it into your document's native representation. The
"Import File"tag illustrates this third origin alongside the other two cases.
@State private var source from "Blank Template" to "Import File" and watch the Text(source) readout open on the import origin instead, showing how a different creation source changes the document's starting point.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 DocumentCreationSourceDemo: View {
@State private var source = "Blank Template"
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Label("New Document", systemImage: "doc.badge.plus")
.font(.headline)
Text("Created from:")
.foregroundStyle(.secondary)
Text(source)
.font(.title3.weight(.semibold))
Picker("Source", selection: $source) {
Text("Blank Template").tag("Blank Template")
Text("From Clipboard").tag("From Clipboard")
Text("Import File").tag("Import File")
}
.pickerStyle(.segmented)
}
.padding()
}
}