Skip to content

Instantly share code, notes, and snippets.

@khanlou
Created October 2, 2021 02:23
Show Gist options
  • Save khanlou/08c8f3a2e419b057f2de09dab3d40394 to your computer and use it in GitHub Desktop.
Save khanlou/08c8f3a2e419b057f2de09dab3d40394 to your computer and use it in GitHub Desktop.
import SwiftUI
struct IdentifiableError: Identifiable {
let error: Error
var id: String {
let nsError = error as NSError
return "\(nsError.domain) \(nsError.code)"
}
}
extension View {
func showError(_ error: Binding<Error?>) -> some View {
let newBinding = Binding(
get: { error.wrappedValue.map({ IdentifiableError(error: $0) }) },
set: { newValue in error.wrappedValue = newValue?.error }
)
return self.alert(item: newBinding, content: { error in
Alert(
title: Text("An error occurred"),
message: Text(error.error.localizedDescription),
dismissButton: .cancel(Text("OK"))
)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment