Skip to content

Instantly share code, notes, and snippets.

@ethanhuang13
Created June 4, 2022 07:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ethanhuang13/3f7aed7e7e1f3f40a93e38512d934250 to your computer and use it in GitHub Desktop.
Save ethanhuang13/3f7aed7e7e1f3f40a93e38512d934250 to your computer and use it in GitHub Desktop.
SwiftUI .alert(item:) for multiple types of Error
//
// ContentView.swift
// ErrorAlert
//
// Created by Ethan Huang on 2022/6/4.
//
import SwiftUI
enum AError: Error {
case a1, a2, a3
var message: String {
switch self {
case .a1:
return "A1"
case .a2:
return "A2"
case .a3:
return "A3"
}
}
}
enum BError: Error {
case b1, b2, b3
var message: String {
switch self {
case .b1:
return "B1"
case .b2:
return "B2"
case .b3:
return "B3"
}
}
}
struct CError: Error {
var message: String { "C" }
}
struct ContentView: View {
enum AlertItem: Identifiable {
case a(AError)
case b(BError)
case c(CError)
var id: String {
switch self {
case .a: return "a"
case .b: return "b"
case .c: return "c"
}
}
}
@State private var alertItem: AlertItem?
var body: some View {
VStack(spacing: 8) {
Button("A1", action: { alertItem = .a(.a1)})
Button("A2", action: { alertItem = .a(.a2)})
Button("A3", action: { alertItem = .a(.a3)})
Button("B1", action: { alertItem = .b(.b1)})
Button("B2", action: { alertItem = .b(.b2)})
Button("B3", action: { alertItem = .b(.b3)})
Button("C", action: { alertItem = .c(.init())})
}
.font(.title)
.alert(item: $alertItem) { item in
switch item {
case let .a(a):
return Alert(title: Text("A"), message: Text(a.message))
case let .b(b):
return Alert(title: Text("B"), message: Text(b.message))
case let .c(c):
return Alert(title: Text("C"), message: Text(c.message))
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment