Bird
Raised Fist0
Swiftprogramming~20 mins

Why enums are powerful in Swift - Challenge Your Understanding

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Enum Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Swift enum code?

Consider this Swift code using enums with associated values. What will it print?

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
BiPad model: 13 Pro
CMac computer
DCompilation error
Attempts:
2 left
💡 Hint

Look at the enum case used to create myDevice and how the switch matches it.

🧠 Conceptual
intermediate
1:30remaining
Why are enums with associated values powerful in Swift?

Which of the following best explains why enums with associated values are powerful in Swift?

AThey allow grouping related values with different types under one type, enabling safer and clearer code.
BThey only store integer values, making them faster than other types.
CThey automatically generate UI elements for each case without extra code.
DThey replace classes and structs entirely in Swift.
Attempts:
2 left
💡 Hint

Think about how enums can hold different kinds of data in one type.

🔧 Debug
advanced
2:00remaining
What error does this Swift enum code produce?

Examine this Swift code snippet. What error will it cause?

Swift
enum Direction {
    case north
    case south
    case east
    case west
}

let dir = Direction.north

switch dir {
case .north:
    print("Going north")
case .south:
    print("Going south")
case .east:
    print("Going east")
// Missing case for .west
}
AError: Cannot use enum cases without raw values
BError: Switch must be exhaustive, missing case for .west
CRuntime error: Unhandled case .west
DNo error, code runs fine
Attempts:
2 left
💡 Hint

Swift requires switch statements on enums to cover all cases or have a default.

🚀 Application
advanced
1:30remaining
How many items are in the resulting enum array?

Given this Swift enum and array, how many elements does allCases contain?

Swift
enum Fruit: CaseIterable {
    case apple
    case banana
    case cherry
}

let allFruits = Fruit.allCases
print(allFruits.count)
ACompilation error
B0
C1
D3
Attempts:
2 left
💡 Hint

Look at how many cases the enum has and what CaseIterable does.

❓ Predict Output
expert
3:00remaining
What is the output of this Swift enum with indirect recursion?

Consider this Swift code using an indirect enum for recursive data. What will it print?

Swift
indirect enum ArithmeticExpression {
    case number(Int)
    case addition(ArithmeticExpression, ArithmeticExpression)
    case multiplication(ArithmeticExpression, ArithmeticExpression)
}

func evaluate(_ expr: ArithmeticExpression) -> Int {
    switch expr {
    case .number(let value):
        return value
    case .addition(let left, let right):
        return evaluate(left) + evaluate(right)
    case .multiplication(let left, let right):
        return evaluate(left) * evaluate(right)
    }
}

let expr = ArithmeticExpression.addition(
    .number(2),
    .multiplication(
        .number(3),
        .number(4)
    )
)

print(evaluate(expr))
A24
B20
C14
DCompilation error due to recursion
Attempts:
2 left
💡 Hint

Calculate the expression step by step: 2 + (3 * 4).

Practice

(1/5)
1. What is one main reason enums are powerful in Swift?
easy
A. They group related values clearly and safely.
B. They allow any type of value without restrictions.
C. They automatically generate user interfaces.
D. They replace all classes and structs.

Solution

  1. Step 1: Understand enum purpose

    Enums group related values into a clear set, making code safer and easier to read.
  2. Step 2: Compare options

    Options A, B, and C describe features not true for enums. Only They group related values clearly and safely. correctly states their main power.
  3. Final Answer:

    They group related values clearly and safely. -> Option A
  4. Quick Check:

    Enums group related values = D [OK]
Hint: Enums group related values safely and clearly [OK]
Common Mistakes:
  • Thinking enums allow any value type without limits
  • Confusing enums with UI components
  • Believing enums replace classes and structs
2. Which of the following is the correct syntax to define an enum in Swift?
easy
A. enum Direction: String { north, south, east, west }
B. enum Direction = { north, south, east, west }
C. enum Direction { north; south; east; west }
D. enum Direction { case north, south, east, west }

Solution

  1. Step 1: Recall enum syntax

    In Swift, enums use the keyword 'enum' followed by cases declared with 'case' keyword separated by commas.
  2. Step 2: Check each option

    enum Direction { case north, south, east, west } uses correct syntax. enum Direction = { north, south, east, west } uses '=' which is invalid. enum Direction: String { north, south, east, west } misses 'case' keyword. enum Direction { north; south; east; west } uses semicolons incorrectly.
  3. Final Answer:

    enum Direction { case north, south, east, west } -> Option D
  4. Quick Check:

    Correct enum syntax uses 'case' keyword = C [OK]
Hint: Remember enum cases start with 'case' keyword [OK]
Common Mistakes:
  • Using '=' instead of '{ }' for enum body
  • Omitting 'case' keyword before cases
  • Separating cases with semicolons instead of commas
3. What will be the output of this Swift code?
enum Result {
    case success(String)
    case failure(String)
}

let outcome = Result.success("Done")
switch outcome {
case .success(let message):
    print("Success: \(message)")
case .failure(let error):
    print("Failure: \(error)")
}
medium
A. Success: error
B. Failure: Done
C. Success: Done
D. Compilation error

Solution

  1. Step 1: Understand enum with associated values

    The enum Result has two cases with associated String values. The variable 'outcome' is assigned .success("Done").
  2. Step 2: Analyze switch statement

    The switch matches .success case, extracts 'message' as "Done", and prints "Success: Done".
  3. Final Answer:

    Success: Done -> Option C
  4. Quick Check:

    Matching .success prints message = A [OK]
Hint: Match enum cases with associated values carefully [OK]
Common Mistakes:
  • Confusing success and failure cases
  • Forgetting to extract associated values
  • Expecting compilation error due to associated values
4. Identify the error in this Swift enum code:
enum Status {
    case ready
    case waiting
    case error(String)
}

let current = Status.error
print(current)
medium
A. Enum cases cannot have associated values.
B. Missing associated value for 'error' case.
C. Cannot print enum values directly.
D. Enum must have raw values.

Solution

  1. Step 1: Check enum definition

    The 'error' case requires a String associated value, but 'current' is assigned without one.
  2. Step 2: Understand assignment error

    Assigning 'Status.error' without a String causes a compile-time error because associated values are mandatory.
  3. Final Answer:

    Missing associated value for 'error' case. -> Option B
  4. Quick Check:

    Associated values must be provided = A [OK]
Hint: Provide associated values when required by enum case [OK]
Common Mistakes:
  • Assigning enum case with associated value without value
  • Thinking enums cannot have associated values
  • Assuming printing enum directly causes error
5. Given this enum with associated values, how can you extract the associated String from a variable of type Response?
enum Response {
    case data(String)
    case error(Int, String)
}

let reply = Response.error(404, "Not Found")

Which code snippet correctly extracts the error message?
hard
A. if case let .error(code, message) = reply { print(message) }
B. if reply == .error { print("Error") }
C. switch reply { case .data(let msg): print(msg) default: break }
D. let message = reply.errorMessage

Solution

  1. Step 1: Understand enum with multiple associated values

    The 'error' case has two associated values: an Int and a String. To get the message, both must be extracted.
  2. Step 2: Analyze extraction methods

    if case let .error(code, message) = reply { print(message) } uses pattern matching with 'if case let' to extract both values and print the message. Options A, C, and D are invalid syntax or incomplete.
  3. Final Answer:

    if case let .error(code, message) = reply { print(message) } -> Option A
  4. Quick Check:

    Pattern match to extract associated values = B [OK]
Hint: Use 'if case let' to extract associated values from enums [OK]
Common Mistakes:
  • Trying to compare enum with associated values directly
  • Ignoring associated values in switch or if
  • Assuming enum has properties like 'errorMessage'
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