How to display Alerts with different messages in SwiftUI in a simple and elegant way ?

While building a SwiftUI application, I had to find a way to display an Alert with custom messages depending on errors returned by my API reponse. It turns out this is not trivial as we can only have a single .alert() container in our ContentView. Here is a nice elegant way to achieve this.

If we look at the documentation, we observe that there are two ways to initialise an alert view :

  • the first and most used using the 'isPresented' binding
  • the second using the 'item' binding

Using the second way, we can create and display different alerts depending on a state variable of type Identifiable.

First, we have to create a struct of type Identifiable that will hold our different Alerts choices :

We also create an optional state variable that will enable to trigger and show the required Alert.

Then, we create a builder method to build the Alert depending on our state variable.

Finally, we update our alert view holder to call the builder method and build the Alert depending on our alertID variable :

And voilà ! We just have to change the state variable alertID with the value we want as following :

This will in turn trigger a refresh of the View, call the builder method and display our Alert to the user. We can even bind this state variable to another view in order to trigger the alert from it. This was very helpful to me to handle errors returned by my API and display them to the user.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Valentin Quelquejay

🇨🇭Cybersecurity student. DJ & Musician. Interested about too much things. Improving every minute.