0
0
iOS Swiftmobile~20 mins

Enums with associated values in iOS Swift - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Payment Method Selector
This screen lets users pick a payment method and shows details based on their choice using enums with associated values.
Target UI
-------------------------
| Payment Method Selector |
-------------------------
| [ ] Credit Card        |
| [ ] PayPal             |
| [ ] Cash               |
-------------------------
| Details:               |
|                        |
|                        |
|                        |
-------------------------
Use an enum with associated values to represent payment methods: Credit Card (number, expiry), PayPal (email), Cash (no data).
Show three selectable options with radio buttons or checkmarks.
When user selects a method, display its details below.
Use SwiftUI for UI and state management.
Starter Code
iOS Swift
import SwiftUI

struct PaymentMethodSelectorView: View {
    // TODO: Define enum PaymentMethod with associated values here

    @State private var selectedMethod: PaymentMethod? = nil

    var body: some View {
        VStack(alignment: .leading, spacing: 20) {
            Text("Payment Method Selector")
                .font(.title)
                .padding(.bottom, 10)

            // TODO: Add selection buttons here

            Text("Details:")
                .font(.headline)

            // TODO: Show details of selected payment method here

            Spacer()
        }
        .padding()
    }
}

struct PaymentMethodSelectorView_Previews: PreviewProvider {
    static var previews: some View {
        PaymentMethodSelectorView()
    }
}
Task 1
Task 2
Task 3
Solution
iOS Swift
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.

Final Result
Completed Screen
-------------------------
| Payment Method Selector |
-------------------------
| (●) Credit Card         |
| ( ) PayPal             |
| ( ) Cash               |
-------------------------
| Details:               |
| Card Number: 1234 5678 |
| 9012 3456              |
| Expiry Date: 12/24     |
-------------------------
Tapping a payment method circle selects it and fills the circle.
Details below update to show the selected payment method's info.
If no method is selected, details show a prompt message.
Stretch Goal
Add a button to clear the selection and reset the details area.
💡 Hint
Add a 'Clear Selection' button that sets selectedMethod to nil.