How it works
An Alert represents a modal interruption that surfaces important information and asks the user to acknowledge it or choose between a small number of actions. Reach for it when your app needs the person's immediate attention before continuing — confirming a destructive change, reporting an error, or noting that an operation finished. Because an alert is system-presented, the framework owns its appearance and dismissal; your role is to declare when it should appear and what choices it offers. In modern SwiftUI you typically configure one through the alert(_:isPresented:actions:message:) modifier rather than constructing the structure directly.
Drive presentation with a bound condition
An alert is presented declaratively: you bind it to a piece of state, and the framework shows or hides it as that value changes. In the example the
alertmodifier takesisPresented: $showing, whereshowingis an@State private var. Setting it totruepresents the alert; the system flips it back tofalsewhen the alert is dismissed.Give it a title
The first argument is the alert's title — a short, plain-language summary of what happened or what is being asked. Here it is the string
"Saved", which appears as the prominent heading at the top of the alert.Supply actions in the actions closure
The trailing
actionsclosure defines the buttons the user can tap to respond and dismiss the alert. The example provides a singleButton("OK", role: .cancel) { }; the.cancelrole marks it as the dismissing action so the system can style and position it accordingly. If you provide no buttons, SwiftUI adds a default dismiss button for you.Add explanatory text with the message closure
The optional
message:closure provides secondary detail shown beneath the title. In the example it returnsText("Your changes were saved successfully."), which expands on the title without repeating it. Keep the message concise — the alert is meant to be read at a glance.
Button("Undo") { } alongside the existing Button("OK", role: .cancel) in the actions closure to see how the alert lays out and prioritizes multiple choices.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 AlertDemo: View {
@State private var showing = true
var body: some View {
Text("Document saved")
.padding()
.alert("Saved", isPresented: $showing) {
Button("OK", role: .cancel) { }
} message: {
Text("Your changes were saved successfully.")
}
}
}