Skip to content

Instantly share code, notes, and snippets.

@surakamy
Last active July 17, 2021 20:06
Show Gist options
  • Save surakamy/4e7904d4923c2d790bb5ae1350126b4e to your computer and use it in GitHub Desktop.
Save surakamy/4e7904d4923c2d790bb5ae1350126b4e to your computer and use it in GitHub Desktop.
SwiftUI Alert example using enum
import SwiftUI
enum Message {
/// A message and OK button
case information(body: String)
/// A message and OK button
case warning(body: String)
/// A question with YES and NO buttons
case confirmation(body: String, action: () -> Void)
/// A question about destractive action with `action` and CANCEL buttons
case destruction(body: String, label: String, action: () -> Void)
}
extension Message: Identifiable {
var id: String { String(reflecting: self) }
}
extension Message {
/// Builder of an Alert
func show() -> Alert {
switch self {
case let .confirmation(body, action):
return Alert(
title: Text("Confirmation"),
message: Text(body),
primaryButton: .default(Text("YES"), action: action),
secondaryButton: .cancel(Text("NO")))
case let .information(body):
return Alert(
title: Text("Information"),
message: Text(body))
case let .warning(body):
return Alert(
title: Text("Warning"),
message: Text(body))
case let .destruction(body, label, action):
return Alert(
title: Text("Confirmation"),
message: Text(body),
primaryButton: .destructive(Text(label), action: action),
secondaryButton: .cancel())
}
}
}
extension View {
func alert(with message: Binding<Message?>) -> some View {
self.alert(item: message) { $0.show() }
}
}
struct ContentView: View {
var variants: [Message] = [
.confirmation(body: "Sure?", action: {
print("Confirmed")
}),
.destruction(body: "Are you want to delete files?", label: "DELETE", action: {
print("Deleted")
}),
.warning(body: "You reached the limit!"),
.information(body: "Rest is what your body needs.")
]
@State var message: Message? = nil
var body: some View {
Button(action: {
self.message = self.variants.randomElement()!
}) {
Text("Let's alert")
}
.alert(with: $message)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment