SwiftUI Alert and Sheets in a Dynamic and Easy Way
One of the struggling topics a learner faces with SwiftUI is presenting alerts and sheets. SwiftUI brings a cool reactive syntax, but sometimes it also has some hassles. In this article, we’ll look at a dynamic, easy way to show a SwiftUI alert or sheet.
In Summary
We store alert and sheets in containers. Containers are stored in the view model. By assigning values(alert or sheet) to the containers, the view updates and shows the alert or sheet.
Starting from scratch
We create 2 container classes as helpers to store alert and sheet views.
[gist id=”9bffb3c0a4694457b5af201eda11e705″ /]
[gist id=”c9f017eb8728aa83b88d582aa2dc6e42″ /]
alert property is the native alert struct in SwiftUI.
view property is the view we wish to show as sheet.
How we will use containers?
We have a view model that’s connected to our main view, ContentView.
[gist id=”3b83291417c7d66efe42738fae78da12″ /]
The view model stores alert and sheet containers, which gives us the flexibility to show them from the view model. Our view can also show them.
[gist id=”1bf50fe1ddd9dfb8e9dfac3a03f6d087″ /]
All we need to do is fill out the alert and sheet properties. When we pass a value to the alert or sheet containers in the view model, they will show up.
P.S. Do not forget to put the StateObject prefix to viewModel property at the 2. line of the class. It triggers the view if there is a change in the view model. More details
Showing our SwiftUI Alert
In the content view’s onAppear block, we can make a trigger to test them. You can put the trigger wherever you’d like afterwards.
[gist id=”61e7d4246ba35b0563f2a95d812bb601″ /]
SheetView is just and empty view that I created.
P.S. Do not forget to use AnyView for the sheet view you will show.
Conclusion
One of the benefits this approach provides is the logic can be handled in the view model. Since we just pass the alert or sheet, UI does not care about which view it will show by a condition such as switch-case or if-else blocks. Those blocks make the view dirty and we get rid of them.



