Bird
Raised Fist0
iOS Swiftmobile~20 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of using enum with associated values in Swift?
easy
A. To store extra data along with each enum case
B. To create a class with multiple methods
C. To define global constants
D. To write loops more efficiently

Solution

  1. Step 1: Understand enum basics

    An enum groups related values under one type.
  2. Step 2: Recognize associated values role

    Associated values let each case hold extra data, like a number or string.
  3. Final Answer:

    To store extra data along with each enum case -> Option A
  4. Quick Check:

    Enums with associated values store extra data [OK]
Hint: Remember: associated values add data to enum cases [OK]
Common Mistakes:
  • Confusing enums with classes
  • Thinking enums only hold fixed values
  • Mixing associated values with raw values
2. Which of the following is the correct syntax to define an enum case with an associated value of type String?
easy
A. case name = String
B. case name(String)
C. case name: String
D. case name -> String

Solution

  1. Step 1: Recall enum case syntax with associated values

    Use parentheses after the case name to specify the type of associated value.
  2. Step 2: Match correct syntax

    Only case name(String) uses parentheses correctly.
  3. Final Answer:

    case name(String) -> Option B
  4. Quick Check:

    Use parentheses for associated value types [OK]
Hint: Use parentheses to declare associated value types [OK]
Common Mistakes:
  • Using colon instead of parentheses
  • Assigning value with equals sign
  • Using arrow notation
3. Given the enum and code below, what will be printed?
enum Result {
  case success(String)
  case failure(Int)
}

let result = Result.success("Done")
switch result {
case .success(let message):
  print(message)
case .failure(let code):
  print("Error \(code)")
}
medium
A. failure
B. Error Done
C. Done
D. Error 0

Solution

  1. Step 1: Identify enum case used

    The variable result is .success("Done").
  2. Step 2: Follow switch matching

    The switch matches .success(let message) and prints the message "Done".
  3. Final Answer:

    Done -> Option C
  4. Quick Check:

    Matching case prints associated string [OK]
Hint: Match enum cases to print associated values [OK]
Common Mistakes:
  • Printing the enum case name instead of value
  • Confusing success and failure cases
  • Not using let to extract associated value
4. What is wrong with this enum and switch code?
enum Direction {
  case up(Int)
  case down(Int)
}

let dir = Direction.up(10)
switch dir {
case .up:
  print("Going up")
case .down:
  print("Going down")
}
medium
A. Switch cases must extract associated values with let
B. Enum cases cannot have associated values
C. Variable dir is not initialized correctly
D. Switch must have a default case

Solution

  1. Step 1: Check enum cases with associated values

    Cases up and down have Int associated values.
  2. Step 2: Analyze switch cases

    Switch cases .up and .down do not extract the Int value with let, causing a compile error.
  3. Final Answer:

    Switch cases must extract associated values with let -> Option A
  4. Quick Check:

    Extract associated values in switch cases [OK]
Hint: Always use let to get associated values in switch [OK]
Common Mistakes:
  • Ignoring associated values in switch
  • Thinking default case is mandatory
  • Wrong enum initialization
5. You want to model a network response enum with cases success carrying a String message, failure carrying an Int error code, and loading with no data. Which is the correct enum definition?
hard
A. enum NetworkResponse { case success(String) case failure(String) case loading(Int) }
B. enum NetworkResponse { case success case failure case loading }
C. enum NetworkResponse { case success(String, Int) case failure(Int) case loading }
D. enum NetworkResponse { case success(String) case failure(Int) case loading }

Solution

  1. Step 1: Match each case with correct associated value

    success needs a String, failure an Int, loading no data.
  2. Step 2: Check each option

    enum NetworkResponse { case success(String) case failure(Int) case loading } matches exactly: success(String), failure(Int), loading without value.
  3. Final Answer:

    enum NetworkResponse { case success(String) case failure(Int) case loading } -> Option D
  4. Quick Check:

    Define cases with correct associated types [OK]
Hint: Match each case to its exact associated value type [OK]
Common Mistakes:
  • Adding wrong types to cases
  • Combining multiple values in one case incorrectly
  • Assigning associated values to cases that should have none
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard