SwiftUI Multiple AlertView, fix weird SwiftUI Alert Behavior

Unlike SwiftUI, which helps you write code intuitively, Alert seems to be implemented strangely. Once an alert is defined in the parent view, all alerts in the child view are ignored. I don’t know if it’s a bug in SwiftUI or it’s intended, but if you use alert, it’s rare to use just one alert.

Problematic Code

Will this code work?

Will this code work as intended? Not really. Only alert1 will show. Because as I told you, once you defined alert in parent view, all child view alerts are ignored.

Alert2 is never going to show

Fix #1-Define multiple alerts in the same hierarchy

Define multiple alerts in the same hierarchy

This will make your code work as intended.

Fix #2-Add Conditional Statement

Alert with AlertType

I mostly use this approach. But the solution #1 is not bad. Instead of defining multiple alert at the same level of the view, I created enum to divide alert types.

Conclusion

  • Once an alert is defined in the parent view, all alerts in the child view are ignored.
  • To solve this problem, define multiple alerts at the same hierarchy level.
  • Or just show different alerts using conditional statement.

--

--

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
KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!