alert(error:actions:message:)
Presents an alert with a message when an error is present.
Declaration
nonisolated func alert<E, A, M>(error: Binding<E?>, @ContentBuilder actions: (E) -> A, @ContentBuilder message: (E) -> M) -> some View where E : Error, A : View, M : View
Parameters
- error:
A binding to an optional Error. The system presents the alert when the binding’s value is non-nil, and uses the error to generate the alert’s title. When the user presses or taps one of the alert’s actions, the system sets this value to
niland dismisses. The system passes the error to the modifier’s closures. You use this data to populate the fields of an alert that the system displays to the user. If the error is aLocalizedError, itserrorDescriptionwill be used as the title, otherwise, the title will beError/localizedDescription. - actions:
A Contentbuilder returning the alert’s actions.
- message:
A Contentbuilder returning the message for the alert given the current error.
Discussion
In the example below, a form conditionally presents an alert depending upon the value of an error. When the error value isn’t nil, the system presents an alert with an “OK” action.
The title of the alert is inferred from the error’s errorDescription if the error is a LocalizedError; otherwise it will be Error/localizedDescription.
struct TicketPurchase: View {
@State private var error: TicketPurchaseError? = nil
var body: some View {
TicketForm(error: $error)
.alert(error: $error) { _ in
Button("OK") {
// Handle acknowledgement.
}
} message: { error in
Text(error.recoverySuggestion ?? "Try again later.")
}
}
}All actions in an alert dismiss the alert after the action runs. The default button is shown with greater prominence. You can influence the default button by assigning it the defaultAction keyboard shortcut.
The system may reorder the buttons based on their role and prominence.
If no actions are present, the system includes a standard “OK” action. No default cancel action is provided. If you want to show a cancel action, use a button with a role of cancel.
On iOS, tvOS, and watchOS, alerts only support controls with labels that are Text. Passing any other type of view results in the content being omitted.
This modifier creates a Text view for the title on your behalf, and treats the localized key similar to init(_:tableName:bundle:comment:). See Text for more information about localizing strings.
See Also
Presenting an alert
AlertScenealert(_:isPresented:actions:)alert(_:isPresented:presenting:actions:)alert(_:item:actions:)alert(error:actions:)alert(isPresented:error:actions:)alert(_:isPresented:actions:message:)alert(_:isPresented:presenting:actions:message:)alert(_:item:actions:message:)alert(isPresented:error:actions:message:)