History
Loading...
Loading...
September 5, 2025
alert(item:) instead of boolean flags. Create a simple AlertItem struct that conforms to Identifiable to handle different alert types cleanly and avoid the common pitfall of alerts not showing when triggered rapidly.Using `AlertItem` with `Identifiable` creates a robust system for managing different types of alerts. The optional binding automatically handles showing and dismissing alerts, while the struct encapsulates all alert-related data including custom actions.
struct AlertItem: Identifiable {
let id = UUID()
let title: String
let message: String
let primaryAction: Alert.Button?
init(title: String, message: String, primaryAction: Alert.Button? = nil) {
self.title = title
self.message = message
self.primaryAction = primaryAction
}
}
struct ContentView: View {
@State private var alertItem: AlertItem?
var body: some View {
VStack {
Button("Show Success Alert") {
alertItem = AlertItem(
title: "Success",
message: "Operation completed successfully"
)
}
Button("Show Error Alert") {
alertItem = AlertItem(
title: "Error",
message: "Something went wrong",
primaryAction: .destructive(Text("Retry")) {
// Retry logic
}
)
}
}
.alert(item: $alertItem) { item in
if let action = item.primaryAction {
return Alert(
title: Text(item.title),
message: Text(item.message),
primaryButton: action,
secondaryButton: .cancel()
)
} else {
return Alert(
title: Text(item.title),
message: Text(item.message)
)
}
}
}
}This approach prevents race conditions when multiple alerts are triggered quickly, provides better type safety, makes alerts more testable, and creates a scalable pattern that can easily accommodate new alert types without adding more state variables.