TechnologiesSwiftUIPresentation and Dialogs

Alert struct

iOSmacOStvOSwatchOSvisionOS✓ renders

A representation of an alert presentation.

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.

  1. 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 alert modifier takes isPresented: $showing, where showing is an @State private var. Setting it to true presents the alert; the system flips it back to false when the alert is dismissed.

  2. 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.

  3. Supply actions in the actions closure

    The trailing actions closure defines the buttons the user can tap to respond and dismiss the alert. The example provides a single Button("OK", role: .cancel) { }; the .cancel role 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.

  4. Add explanatory text with the message closure

    The optional message: closure provides secondary detail shown beneath the title. In the example it returns Text("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.

Try it — Add a second 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.

Alert.swift
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.")
            }
    }
}
Live preview
Document saved Saved OK
Document saved Saved OK
swift → lexer → parser → sema → uiir → canvas Open in Studio ↗
What's new in SwiftUI 27 →