How it works
A KeyEquivalent represents a single key on the keyboard that can trigger an action — the key half of a keyboard shortcut. Where a shortcut answers "which keys?", KeyEquivalent is the piece that names the key itself, leaving any modifier keys to be specified separately. Reach for it whenever you bind a control to the keyboard, most commonly by passing it to the keyboardShortcut(_:modifiers:) modifier so a button or command can be invoked without a tap or click.
Name a key with a character literal or named constant
KeyEquivalentis expressible by a singleCharacter, so you can write"a"directly, or use one of its named static constants for keys that have no convenient literal. The example uses the constantKeyEquivalent.returnto refer to the Return key rather than trying to spell it as a character.Reach for the named constants for special keys
Keys like Return, Escape, Delete, Tab, the arrows, and Space are exposed as type properties such as
.return,.escape,.tab, and.space. These give you a readable, unambiguous handle on keys you can't type as a plain literal —KeyEquivalent.returnhere stands in for the Return key on its own.Pass it to keyboardShortcut(_:modifiers:)
A
KeyEquivalentbecomes a usable shortcut when you hand it tokeyboardShortcut(_:modifiers:)on a view. The example attaches the modifier to theButton, withKeyEquivalent.returnas the key, so pressing the indicated combination runs the same action as activating the button.Combine the key with modifiers
The key equivalent only describes the base key; modifier keys come from the separate
modifiers:parameter, anEventModifiersset. Passing.commandalongsideKeyEquivalent.returnforms the Command-Return combination shown in the button's title (⌘↩).
KeyEquivalent.return to KeyEquivalent.space (and update the button title to match) to bind the action to Command-Space instead, demonstrating how swapping the key equivalent redefines which key triggers the shortcut.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 KeyEquivalentDemo: View {
@State private var count = 0
var body: some View {
VStack(spacing: 16) {
Text("Count: \(count)")
.font(.title2)
Button("Increment (\u{2318}\u{21A9})") {
count += 1
}
.keyboardShortcut(KeyEquivalent.return, modifiers: .command)
.buttonStyle(.borderedProminent)
}
.padding()
}
}