Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Handle Errors with an Alert in SwiftUI
Written by Team Kodeco

In addition to displaying simple messages, SwiftUI’s alert system can also handle errors. When an error occurs in your app, you can use the alert view modifier to present an alert to the user, allowing them to acknowledge and address the error.

The error parameter accepts a LocalizedError object. The alert’s title is automatically inferred from the error’s errorDescription. You can then use the error object to customize the alert’s message and actions.

Consider the following example:

struct ContentView: View {
  @State private var error: MyError? = nil
  @State private var showAlert = false

  var body: some View {
    Button("Trigger Error") {
      error = MyError.someError
      showAlert = true
    }
    .alert(isPresented: $showAlert, error: error) { _ in
      Button("OK") {
        // Handle acknowledgement.
        showAlert = false
      }
    } message: { error in
      Text(error.recoverySuggestion ?? "Try again later.")
    }
  }
}

enum MyError: LocalizedError {
  case someError

  var errorDescription: String? {
    switch self {
    case .someError:
      return "Something went wrong"
    }
  }

  var recoverySuggestion: String? {
    switch self {
    case .someError:
      return "Please try again."
    }
  }
}

Tap Trigger Error and your preview should look like this:

An example of using an alert to display an error in SwiftUI.
An example of using an alert to display an error in SwiftUI.

In this example, tapping the Trigger Error button triggers an error and sets the showAlert state to true, which in turn presents the alert. The alert’s title is generated from the error’s errorDescription and its message is generated from the error’s recoverySuggestion.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.