import SwiftUI
struct PaymentMethodSelectorView: View {
enum PaymentMethod: Identifiable {
case creditCard(number: String, expiry: String)
case paypal(email: String)
case cash
var id: String {
switch self {
case .creditCard:
return "creditCard"
case .paypal:
return "paypal"
case .cash:
return "cash"
}
}
}
@State private var selectedMethod: PaymentMethod? = nil
var body: some View {
VStack(alignment: .leading, spacing: 20) {
Text("Payment Method Selector")
.font(.title)
.padding(.bottom, 10)
Button(action: {
selectedMethod = .creditCard(number: "1234 5678 9012 3456", expiry: "12/24")
}) {
HStack {
Image(systemName: selectedMethod?.id == "creditCard" ? "circle.fill" : "circle")
Text("Credit Card")
}
}
.buttonStyle(PlainButtonStyle())
Button(action: {
selectedMethod = .paypal(email: "user@example.com")
}) {
HStack {
Image(systemName: selectedMethod?.id == "paypal" ? "circle.fill" : "circle")
Text("PayPal")
}
}
.buttonStyle(PlainButtonStyle())
Button(action: {
selectedMethod = .cash
}) {
HStack {
Image(systemName: selectedMethod?.id == "cash" ? "circle.fill" : "circle")
Text("Cash")
}
}
.buttonStyle(PlainButtonStyle())
Text("Details:")
.font(.headline)
Group {
switch selectedMethod {
case .creditCard(let number, let expiry):
Text("Card Number: \(number)\nExpiry Date: \(expiry)")
case .paypal(let email):
Text("PayPal Email: \(email)")
case .cash:
Text("Pay with cash upon delivery.")
case .none:
Text("No payment method selected.")
}
}
.padding()
.background(Color.gray.opacity(0.1))
.cornerRadius(8)
Spacer()
}
.padding()
}
}
struct PaymentMethodSelectorView_Previews: PreviewProvider {
static var previews: some View {
PaymentMethodSelectorView()
}
}We created an enum PaymentMethod with three cases, each holding different data using associated values. The Identifiable protocol helps us identify each case uniquely for UI updates.
Three buttons let the user pick a payment method. When tapped, they set selectedMethod with the appropriate enum case and data.
The details section uses a switch on selectedMethod to show the right information for the chosen payment method.
This approach shows how enums with associated values can store different data types cleanly and how SwiftUI updates the UI reactively when state changes.