How it works
EmptyCommands is a commands value that contributes nothing to a scene's command hierarchy. It conforms to the Commands protocol so it can stand in anywhere a Commands value is expected — inside a .commands modifier or a @CommandsBuilder — while leaving the app's menus and keyboard shortcuts untouched. Reach for it when a code path must produce a Commands value but you want it to be a no-op, such as the neutral branch of a conditional, the default of a switch, or a placeholder while you build a command set up incrementally.
Construct it with EmptyCommands()
The type has a single no-argument initializer that yields an empty set of commands. In the example,
EmptyCommands()is the entire body of the commands group, producing a value that satisfies the Commands requirement without declaring any menu or shortcut.Return it from a @CommandsBuilder
Because EmptyCommands conforms to Commands, it is a valid result for any result-builder context that expects commands. Here the computed property
noMenusis annotated@CommandsBuilderand returnssome Commands, andEmptyCommands()is what it hands back — the type-erased opaque result is still a fully formed, if empty, commands value.Plug it into a scene's .commands modifier
A Commands value is normally attached to a Scene through the commands(content:) modifier, where it merges into the app's menu bar. Supplying
EmptyCommands()there means the scene adds no items of its own, so the surrounding system and inherited commands are presented unchanged.Use it as the neutral branch in conditional commands
Inside a command builder you can choose between command groups based on state; EmptyCommands gives you a value for the "add nothing" case. Swapping in
EmptyCommands()on one branch lets the other branch contribute real CommandGroup or CommandMenu content while this branch stays a deliberate no-op.
EmptyCommands() in the noMenus property with a CommandMenu("Extras") { Button("Ping") {} } and observe a new menu appear, confirming that EmptyCommands was the reason no menu was being added.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 EmptyCommandsDemo: View {
// EmptyCommands is the no-op Commands value used in a Scene's
// .commands { } builder when you want to add nothing.
@CommandsBuilder var noMenus: some Commands {
EmptyCommands()
}
var body: some View {
VStack(spacing: 12) {
Image(systemName: "menubar.rectangle")
.font(.largeTitle)
Text("EmptyCommands")
.font(.headline)
Text("A Commands value that adds no menu items.")
.font(.caption)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
}
.padding()
}
}