Bird
Raised Fist0
Swiftprogramming~20 mins

Enum with switch pattern matching in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Enum Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of switch with enum and associated values
What is the output of this Swift code using enum and switch pattern matching?
Swift
enum Device {
    case iPhone(model: String)
    case iPad(model: String)
    case mac
}

let myDevice = Device.iPhone(model: "13 Pro")

switch myDevice {
case .iPhone(let model):
    print("iPhone model: \(model)")
case .iPad(let model):
    print("iPad model: \(model)")
case .mac:
    print("Mac computer")
}
AiPhone model: 13 Pro
BMac computer
CiPad model: 13 Pro
DCompilation error
Attempts:
2 left
💡 Hint
Look at the enum case and the associated value passed to it.
❓ Predict Output
intermediate
2:00remaining
Switch pattern matching with multiple associated values
What will this Swift code print when run?
Swift
enum Result {
    case success(code: Int, message: String)
    case failure(error: String)
}

let response = Result.success(code: 200, message: "OK")

switch response {
case .success(let code, let message) where code == 200:
    print("Success with code 200: \(message)")
case .success(let code, let message):
    print("Success with code \(code): \(message)")
case .failure(let error):
    print("Failure: \(error)")
}
ACompilation error
BSuccess with code 200: OK
CFailure: OK
DSuccess with code 200: failure
Attempts:
2 left
💡 Hint
Check the where clause in the first case of the switch.
🔧 Debug
advanced
2:00remaining
Identify the error in switch pattern matching with enum
What error does this Swift code produce when compiled?
Swift
enum Status {
    case ready
    case loading(progress: Int)
    case error(message: String)
}

let currentStatus = Status.loading(progress: 50)

switch currentStatus {
case .ready:
    print("Ready")
case .loading:
    print("Loading")
case .error(let message):
    print("Error: \(message)")
}
ARuntime error: Unexpected nil value
BNo error, prints: Loading
CError: Enum case 'loading' not handled correctly
DError: Missing associated value pattern in case .loading
Attempts:
2 left
💡 Hint
Check how the .loading case is matched in the switch.
🧠 Conceptual
advanced
1:30remaining
Understanding exhaustive switch with enums
Why does Swift require the switch statement to be exhaustive when switching over enums?
ATo force the programmer to use if-else instead of switch
BBecause Swift does not support default cases in switch statements
CTo ensure all possible enum cases are handled, preventing runtime errors
DBecause enums can only have one case
Attempts:
2 left
💡 Hint
Think about safety and completeness in code.
❓ Predict Output
expert
2:30remaining
Output of nested enum with switch pattern matching
What is the output of this Swift code with nested enums and switch pattern matching?
Swift
enum Network {
    enum Response {
        case success(data: String)
        case failure(code: Int)
    }
    case request(url: String, response: Response)
}

let netCall = Network.request(url: "example.com", response: .failure(code: 404))

switch netCall {
case .request(let url, let response):
    switch response {
    case .success(let data):
        print("Success from \(url): \(data)")
    case .failure(let code) where code >= 400:
        print("Error \(code) from \(url)")
    default:
        print("Other response from \(url)")
    }
}
AError 404 from example.com
BSuccess from example.com: failure
COther response from example.com
DCompilation error
Attempts:
2 left
💡 Hint
Look at the nested switch and the where clause condition.

Practice

(1/5)
1. What is the main purpose of using an enum with associated values in Swift?
easy
A. To group related values and store extra data in each case
B. To create a class with multiple methods
C. To define a function that returns multiple values
D. To declare a variable that can only hold integers

Solution

  1. Step 1: Understand enum basics

    An enum groups related values under one type, making code organized.
  2. Step 2: Recognize associated values

    Enums with associated values can store extra data for each case, like a label or number.
  3. Final Answer:

    To group related values and store extra data in each case -> Option A
  4. Quick Check:

    Enum with associated values = group + extra data [OK]
Hint: Enums group related data with extra info easily [OK]
Common Mistakes:
  • Confusing enums with classes
  • Thinking enums only hold fixed values
  • Assuming enums are functions
2. Which of the following is the correct syntax to match an enum case with associated values using switch in Swift?
easy
A. case .someCase(let value):
B. case someCase = value:
C. case .someCase => value:
D. case someCase(value) {

Solution

  1. Step 1: Recall switch case syntax for enums

    In Swift, to match an enum case with associated values, use case .caseName(let variable):.
  2. Step 2: Identify correct pattern

    case .someCase(let value): uses the correct dot syntax and binding with let.
  3. Final Answer:

    case .someCase(let value): -> Option A
  4. Quick Check:

    Switch enum case with let binding = case .someCase(let value): [OK]
Hint: Use dot and let to bind enum associated values [OK]
Common Mistakes:
  • Missing dot before case name
  • Using = instead of :
  • Wrong arrow or braces syntax
3. What will be the output of this Swift code?
enum Direction {
    case north, south, east, west
}

let dir = Direction.east

switch dir {
case .north:
    print("Going North")
case .south:
    print("Going South")
case .east:
    print("Going East")
case .west:
    print("Going West")
}
medium
A. No output
B. Going North
C. Going West
D. Going East

Solution

  1. Step 1: Identify enum value assigned

    The variable dir is assigned Direction.east.
  2. Step 2: Match switch case

    The switch matches .east case and prints "Going East".
  3. Final Answer:

    Going East -> Option D
  4. Quick Check:

    dir = east prints "Going East" [OK]
Hint: Match enum value to switch case to find output [OK]
Common Mistakes:
  • Confusing enum case names
  • Forgetting to include all cases
  • Assuming default case runs
4. Identify the error in this Swift code using enum and switch:
enum Result {
    case success(Int)
    case failure(String)
}

let res = Result.success(10)

switch res {
case .success(let value):
    print("Value: \(value)")
case failure(let message):
    print("Error: \(message)")
}
medium
A. Switch statement missing default case
B. Wrong associated value type for 'success'
C. Missing dot before 'failure' in switch case
D. Enum cases cannot have associated values

Solution

  1. Step 1: Check switch case syntax

    In switch, enum cases must be prefixed with a dot, like .failure.
  2. Step 2: Identify missing dot

    The second case uses failure without a dot, causing a syntax error.
  3. Final Answer:

    Missing dot before 'failure' in switch case -> Option C
  4. Quick Check:

    Enum case in switch needs dot prefix [OK]
Hint: Always prefix enum cases with dot in switch [OK]
Common Mistakes:
  • Omitting dot before enum case in switch
  • Confusing associated value types
  • Forgetting to handle all cases
5. Given this enum and function, what will describeShape(.rectangle(width: 5, height: 10)) print?
enum Shape {
    case circle(radius: Double)
    case rectangle(width: Double, height: Double)
    case point
}

func describeShape(_ shape: Shape) {
    switch shape {
    case .circle(let r):
        print("Circle with radius \(r)")
    case .rectangle(let w, let h):
        print("Rectangle \(w) x \(h)")
    case .point:
        print("Just a point")
    }
}
hard
A. Circle with radius 5.0
B. Rectangle 5.0 x 10.0
C. Just a point
D. Syntax error in switch

Solution

  1. Step 1: Identify enum case and associated values

    The input is .rectangle(width: 5, height: 10), so width = 5 and height = 10.
  2. Step 2: Match switch case and print

    The switch matches .rectangle(let w, let h) and prints "Rectangle 5.0 x 10.0".
  3. Final Answer:

    Rectangle 5.0 x 10.0 -> Option B
  4. Quick Check:

    Rectangle case prints dimensions [OK]
Hint: Match enum case and extract all associated values [OK]
Common Mistakes:
  • Using wrong variable names in case
  • Missing multiple associated values in pattern
  • Assuming default case runs
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