How it works
DismissWindowAction is a callable action you invoke to programmatically close a window scene that your app previously opened. SwiftUI places an instance in the environment under the dismissWindow key, so any view can reach for it to dismiss a window by its identifier or presented value without holding a reference to the scene itself. Reach for it when a window's own content needs to close that window — for example a settings panel with a Close button, or an auxiliary window that finishes its task and should go away.
Read the action from the environment with @Environment(\.dismissWindow)
Because the action is provided by SwiftUI rather than constructed by you, you obtain it through the environment. Declaring
@Environment(\.dismissWindow) private var dismissWindowbinds a localDismissWindowActionvalue that stays current for the view's scene context.Call the action as a function to close the current window
DismissWindowAction conforms to a call-as-function style, so you invoke the stored value directly as
dismissWindow(...)rather than calling a named method. Here theButton("Close Window")action closure calls it to tear down the window when the button is pressed.Target a specific window with the id: parameter
The action accepts arguments that identify which window to close, mirroring the identifiers you assign to your WindowGroup or Window scenes. In the example
dismissWindow(id: "settings")dismisses the scene registered under the"settings"identifier; calling it with no arguments dismisses the window the view currently lives in.Invoke it from any view in the window's hierarchy
Since the action travels through the environment, it is available to deeply nested views, not just the scene's root. The
VStackhere is ordinary layout scaffolding — the meaningful part is that thedismissWindowvalue resolved from the environment can be called from thisButtonto affect the enclosing window.
dismissWindow(id: "settings") to dismissWindow() and observe that the action now closes whichever window the view is shown in rather than the scene registered under "settings".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 DismissWindowActionDemo: View {
@Environment(\.dismissWindow) private var dismissWindow
var body: some View {
VStack(spacing: 16) {
Text("Settings")
.font(.title2.bold())
Button("Close Window") {
dismissWindow(id: "settings")
}
.buttonStyle(.borderedProminent)
}
.padding()
}
}