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 method with computed property
What is the output of this Swift code?
Swift
enum Direction { case north, south, east, west var isVertical: Bool { return self == .north || self == .south } func description() -> String { return isVertical ? "Vertical" : "Horizontal" } } let dir = Direction.east print(dir.description())
Attempts:
2 left
💡 Hint
Check how the computed property 'isVertical' is defined and used in the method.
✗ Incorrect
The enum Direction has a computed property 'isVertical' that returns true only for .north and .south. Since 'dir' is .east, 'isVertical' is false, so description() returns "Horizontal".
❓ Predict Output
intermediate2:00remaining
Computed property with associated values
What will be printed by this Swift code?
Swift
enum Result { case success(Int) case failure(String) var message: String { switch self { case .success(let code): return "Success with code \(code)" case .failure(let error): return "Failed: \(error)" } } } let res = Result.failure("Network error") print(res.message)
Attempts:
2 left
💡 Hint
Look at how the associated value is extracted in the computed property.
✗ Incorrect
The enum case is .failure with associated value "Network error", so the computed property returns "Failed: Network error".
🔧 Debug
advanced2:00remaining
Identify the error in enum method
What error does this Swift code produce when compiled?
Swift
enum Status { case ready, waiting func isReady() -> Bool { switch self { case .ready: return true case .waiting return false } } }
Attempts:
2 left
💡 Hint
Check the switch case syntax carefully.
✗ Incorrect
The case '.waiting' is missing a colon ':' after it, causing a syntax error.
❓ Predict Output
advanced2:00remaining
Computed property returning different types
What is the output of this Swift code?
Swift
enum Measurement { case weight(Double) case count(Int) var description: String { switch self { case .weight(let w): return "Weight: \(w) kg" case .count(let c): return "Count: \(c) items" } } } let m = Measurement.weight(3.5) print(m.description)
Attempts:
2 left
💡 Hint
Check the associated value type and string interpolation.
✗ Incorrect
The enum case is .weight with value 3.5, so the description returns "Weight: 3.5 kg".
🧠 Conceptual
expert2:00remaining
Why use computed properties in enums?
Which of the following best explains why computed properties are useful in Swift enums?
Attempts:
2 left
💡 Hint
Think about what computed properties do in general.
✗ Incorrect
Computed properties let you add dynamic behavior or calculate values based on the enum case and its associated data, without storing extra data.