Creating user-friendly apps means giving users clear feedback. One of the simplest ways to do this in SwiftUI is by showing an alert. Alerts are great for warnings, confirmations, errors, or just saying “Hey, something happened!” If you’re new to SwiftUI or just want a quick refresher, you’re in the right place.
TL;DR
Using alerts in SwiftUI is super easy. You just need a state variable and the .alert modifier. Add a condition and boom — alert appears! This article walks you through everything with examples and tips.
What is an alert?
An alert is a pop-up message that shows brief info and gives users choices, like “OK” or “Cancel”. It’s a simple but powerful way to talk to users. Think of it as your app whispering a quick heads-up.
Why use alerts?
- Warn users before they do something serious like deleting a file.
- Ask for confirmation to prevent mistakes.
- Show messages when something unexpected happens.
SwiftUI makes this very easy. You can add alerts to buttons, screens, and even other alerts (though that gets messy — try not to go alert-ception).
Basic alert example
Let’s jump in with a basic example. Imagine a button that says “Show Alert.” When you tap it, an alert pops up. Here’s how we do that:
import SwiftUI
struct ContentView: View {
@State private var showAlert = false
var body: some View {
VStack {
Button("Show Alert") {
showAlert = true
}
.alert("Hello!", isPresented: $showAlert) {
Button("OK", role: .cancel) { }
}
}
}
}
Let’s break that down:
- @State holds the Boolean flag that toggles the alert.
- Button changes the value of showAlert when tapped.
- .alert watches showAlert and shows the alert box.
Customizing the alert
Want to get fancier? You can customize alerts with multiple buttons and actions. Here’s how to add more options:
.alert("Are you sure?", isPresented: $showAlert) {
Button("Delete", role: .destructive) {
print("Deleted!")
}
Button("Cancel", role: .cancel) { }
}
The role helps SwiftUI understand the purpose of the button. It makes things clearer to users too — destructive buttons might turn red, and cancel ones are usually safe and calm.
When you click Delete here, we can trigger a real action like removing a file or logging out the user. Keep it clean and meaningful.
Showing alerts based on condition
Sometimes you don’t just show alerts on tap. You might need to show one when something breaks, like a network error. Here’s a cool trick using optional alerts with a Bindable condition:
struct AlertItem: Identifiable {
var id = UUID()
var title: String
var message: String
var dismissButton: Alert.Button
}
struct ContentView: View {
@State private var alertItem: AlertItem?
var body: some View {
VStack {
Button("Try Something Risky") {
// Something bad happened!
alertItem = AlertItem(
title: "Oops!",
message: "Something went wrong.",
dismissButton: .default(Text("Got it!"))
)
}
}
.alert(item: $alertItem) { item in
Alert(title: Text(item.title), message: Text(item.message), dismissButton: item.dismissButton)
}
}
}
This is great for more dynamic apps. You can create alerts on the fly and keep your conditions cleaner.
Quick styling tips
- Keep the title short and clear. Don’t write a whole paragraph.
- Use message for more detail, but don’t overload it.
- Use roles like .destructive, .cancel, or .default. It helps with clarity and accessibility.
- Limit buttons. More than 2 can feel cluttered. Try using just one or two.
Alert with TextField? Not so fast!
Want to add a text field to your alert? Sorry — not in SwiftUI (yet). Apple’s built-in alert doesn’t let you do that. But!
You can create a custom modal using a sheet or overlay for that. Here’s a quick idea:
- Create a custom view with a TextField
- Use .sheet to present it
- Use the input inside your app logic
This gives you way more control too. It’s like the DIY version of alerts.
Common mistakes to avoid
We’ve all been there. Alerts don’t show, or they show too much. Here’s what to avoid:
- Forgetting to toggle the binding: If showAlert stays false, nothing happens.
- Multiple alerts on one view: Only one will show. Decide which one is most important.
- Big complicated logic in buttons: Keep your alert actions clean. Call a helper function instead.
Bonus: Using alerts with Enums
Want to clean up your code even more? Use enum-based alert objects. It keeps your logic neat.
enum AlertType: Identifiable {
case error
case logout
var id: Int {
hashValue
}
var data: (title: String, message: String) {
switch self {
case .error:
return ("Error", "Something went wrong.")
case .logout:
return ("Goodbye", "You have been logged out.")
}
}
}
Now use it smoothly in your views with .alert(item:). Less mess, more fun.
Wrap-up
And that’s it! 🌟
Alerts in SwiftUI are simple, clean, and powerful. Once you learn how they work, you can handle just about any situation where the app needs to tap you on the shoulder and say “Heads up.”
Customize them, tie them to state changes, or make them part of bigger flows. You’re in control.
Now go make your app sing (or alert) with clarity!


Leave a Reply