How it works
CommandsBuilder is a result builder that assembles the contents of an app's command hierarchy — the menu items, menu groups, and keyboard shortcuts that populate the menu bar and respond to commands. SwiftUI uses it to let you list several command structures one after another inside a closure and have them combined into a single Commands value, the same way ViewBuilder combines views. Reach for it whenever you supply commands to the system: it is the builder that backs the trailing closures of the .commands modifier and of a Commands group such as CommandMenu, so you rarely name it directly but always write inside it.
Write commands in a @CommandsBuilder closure
Any closure that produces commands is implicitly a CommandsBuilder closure, so you simply list command elements and the builder merges them. In the example the closure passed to .commands holds a single CommandMenu, and the builder is what turns that statement into the Commands value the modifier expects.
Attach the built commands with .commands
The .commands(content:) modifier takes a @CommandsBuilder closure and installs whatever it produces into the app's command hierarchy. Here .commands wraps the menu definitions and connects them to the view containing the Items: \(count) and Menu commands attached below text.
Group related commands with CommandMenu
Inside the builder you place command containers such as CommandMenu, which adds a new top-level menu to the menu bar from its title and a nested @ViewBuilder of controls. The example's CommandMenu("Items") creates an Items menu that holds the buttons defined within it.
Add invokable items as Buttons
The individual commands are ordinary Buttons whose actions run when the menu item is chosen. The Add Item button increments count and the Reset button sets it back to 0, each becoming a selectable entry in the generated menu.
Bind shortcuts with keyboardShortcut()
Because the builder yields real views, you can refine each command with view modifiers — keyboardShortcut() assigns a key equivalent that triggers the command without opening the menu. Applying .keyboardShortcut("n") to the Add Item button lets it fire from the keyboard as well as the menu.
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 CommandsBuilderDemo: View {
@State private var count = 0
var body: some View {
VStack(spacing: 12) {
Text("Items: \(count)")
.font(.title2)
Text("Menu commands attached below")
.font(.footnote)
.foregroundStyle(.secondary)
}
.padding()
.commands {
CommandMenu("Items") {
Button("Add Item") { count += 1 }
.keyboardShortcut("n")
Button("Reset") { count = 0 }
}
}
}
}