# SwiftUI: alert messages

> Learn how to show an alert in SwiftUI using the .alert() modifier and an isPresented boolean, so a message pops up when a condition becomes true.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2021-09-19 | Topics: [Swift](https://flaviocopes.com/tags/swift/) | Canonical: https://flaviocopes.com/swiftui-alert/

A common way to give feedback to users, but also to help you debug your applications sometimes, is to use alerts.

[SwiftUI](https://flaviocopes.com/swiftui-introduction/) provides the `.alert()` modifier that we can use to show an alert based on some condition.

Let's start from this example where we have a `Button` with a counter:

```swift
import SwiftUI

struct ContentView: View {
    @State var count = 0
    
    var body: some View {
        Button("Count: \(count)") {
            self.count += 1
        }
        .font(.title)
    }
}
```

when `count` reaches 10 I want to show an alert message.

How do we do that?

I can add a `showAlert` boolean property to the `ContentView` and edit the content of the `Button` tap action:

```swift
struct ContentView: View {
    @State var count = 0
    @State var showAlert = false
    
    var body: some View {
        Button("Count: \(count)") {
            self.count += 1
            if self.count == 10 {
                showAlert = true
                self.count = 0
            }
        }
        .font(.title)
    }
}
```

When we reach 10, we set `showAlert` to `true` and we set the count to 0.

Then I add the `.alert()` modifier to the `Button` view:

```swift
.alert(isPresented: $showAlert) {
    Alert(title: Text("Great!"), message: Text("You reached 10"))
}
```

This alert is shown only when the `showAlert` property is true. When we dismiss the alert, the `showAlert` property is automatically set to `false`.

Here's the full code:

```swift
struct ContentView: View {
    @State var count = 0
    @State var showAlert = false
    
    var body: some View {
        Button("Count: \(count)") {
            self.count += 1
            if self.count == 10 {
                showAlert = true
                self.count = 0
            }
        }
        .font(.title)
        .alert(isPresented: $showAlert) {
            Alert(title: Text("Great!"), message: Text("You reached 10"))
        }
    }
}
```

Try running the app. The counter starts at 0. Click the button and the counter will increase:

![iPhone simulator showing a SwiftUI button displaying Count: 5](https://flaviocopes.com/images/swiftui-alert/Screen_Shot_2021-09-13_at_18.47.38.png)

Until you reach 10:

![iPhone simulator showing SwiftUI alert popup with title Great! You reached 10 and OK button](https://flaviocopes.com/images/swiftui-alert/Screen_Shot_2021-09-13_at_18.47.42.png)

Then the counter will start again from 0:

![iPhone simulator showing SwiftUI button with counter reset to Count: 0](https://flaviocopes.com/images/swiftui-alert/Screen_Shot_2021-09-13_at_18.47.45.png)
