SwiftUI: Using Alerts to Display Messages
Alert messages are a useful way to provide feedback to users and aid in debugging applications. In SwiftUI, you can leverage the .alert() modifier to display alerts based on certain conditions.
Let’s consider an example where we have a Button with an associated counter:
1 | import SwiftUI |
Suppose we want to show an alert message when the count reaches 10. To achieve this, we can introduce a boolean property showAlert in the ContentView and modify the tap action of the Button as follows:
1 | struct ContentView: View { |
In this updated code, we set showAlert to true and reset the count to 0 when it reaches 10.
Now, let’s add the .alert() modifier to the Button view to display the alert:
1 | .alert(isPresented: $showAlert) { |
This alert will only be shown when the showAlert property is true. Dismissing the alert automatically sets the showAlert property to false.
Here’s the complete code:
1 | struct ContentView: View { |
Try running the app. The counter starts at 0, and clicking the button increments the counter. When the count reaches 10, the alert message is displayed. After dismissing the alert, the counter resets to 0.



tags: [“SwiftUI”, “alerts”, “debugging”, “user feedback”]