Challenge - 5 Problems
Enum Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of enum with raw values
What is the output of this Swift code?
Swift
enum Direction: String { case north = "N" case south = "S" case east = "E" case west = "W" } let dir = Direction.east print(dir.rawValue)
Attempts:
2 left
💡 Hint
Look at the rawValue property of the enum case.
✗ Incorrect
The enum Direction has raw values of type String. The case east has raw value "E". Printing dir.rawValue outputs "E".
❓ Predict Output
intermediate2:00remaining
Enum with associated values output
What will this Swift code print?
Swift
enum Result { case success(Int) case failure(String) } let res = Result.failure("Error") switch res { case .success(let code): print("Success with code \(code)") case .failure(let message): print("Failed: \(message)") }
Attempts:
2 left
💡 Hint
Check which case is assigned to res and what the associated value is.
✗ Incorrect
The enum instance res is .failure with associated value "Error". The switch matches .failure and prints "Failed: Error".
🔧 Debug
advanced2:00remaining
Identify the error in enum declaration
Which option shows the error when compiling this enum declaration?
Swift
enum Color { case red case green case blue case yellow = 4 }
Attempts:
2 left
💡 Hint
Check if enum has raw type when assigning values to cases.
✗ Incorrect
In Swift, enum cases can only have assigned raw values if the enum declares a raw type. Here, Color has no raw type but yellow is assigned 4, causing a compile error.
🧠 Conceptual
advanced2:00remaining
Number of cases in enum
Given this enum, how many cases does it have?
Swift
enum Weekday { case monday, tuesday, wednesday case thursday case friday, saturday, sunday }
Attempts:
2 left
💡 Hint
Count all the cases separated by commas and lines.
✗ Incorrect
The enum Weekday has 7 cases: monday, tuesday, wednesday, thursday, friday, saturday, sunday.
❓ Predict Output
expert3:00remaining
Output of enum with indirect recursive case
What does this Swift code print?
Swift
enum ArithmeticExpression { case number(Int) indirect case addition(ArithmeticExpression, ArithmeticExpression) } let five = ArithmeticExpression.number(5) let four = ArithmeticExpression.number(4) let sum = ArithmeticExpression.addition(five, four) func evaluate(_ expr: ArithmeticExpression) -> Int { switch expr { case .number(let value): return value case .addition(let left, let right): return evaluate(left) + evaluate(right) } } print(evaluate(sum))
Attempts:
2 left
💡 Hint
Think about how the recursive evaluation adds the numbers.
✗ Incorrect
The enum uses indirect case to allow recursion. The evaluate function sums the numbers 5 and 4, resulting in 9.