Skip to content

Instantly share code, notes, and snippets.

@gondo
Forked from simonbs/View+ErrorAlert.swift
Created September 4, 2025 08:27
Show Gist options
  • Save gondo/4fbd565fc6b42545e5a0c9f06894ca9d to your computer and use it in GitHub Desktop.
Save gondo/4fbd565fc6b42545e5a0c9f06894ca9d to your computer and use it in GitHub Desktop.
SwiftUI view modifier for presenting an alert when an error binding has a value.
import SwiftUI
public extension View {
func alert<Message: View, Actions: View>(
_ title: LocalizedStringResource,
presenting error: Binding<Error?>,
@ViewBuilder message: @escaping (Error) -> Message,
@ViewBuilder actions: @escaping () -> Actions
) -> some View {
modifier(
ErrorAlertViewModifier(
title: title,
error: error,
actions: actions,
message: message
)
)
}
func alert<Message: View>(
_ title: LocalizedStringResource,
presenting error: Binding<Error?>,
@ViewBuilder message: @escaping (Error) -> Message
) -> some View {
modifier(
ErrorAlertViewModifier(title: title, error: error) {
Button(role: .cancel) {
error.wrappedValue = nil
} label: {
Text("OK")
}
} message: { error in
message(error)
}
)
}
}
private struct ErrorAlertViewModifier<Message: View, Actions: View>: ViewModifier {
let title: LocalizedStringResource
@Binding var error: Error?
@ViewBuilder let actions: () -> Actions
@ViewBuilder let message: (Error) -> Message
@State private var isAlertPresented = false
private var hasError: Bool {
error != nil
}
func body(content: Content) -> some View {
content
.alert(title, isPresented: $isAlertPresented) {
actions()
} message: {
if let error {
message(error)
}
}
.onChange(of: hasError) { _, newValue in
isAlertPresented = newValue
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment