Challenge - 5 Problems
CaseIterable Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate1:30remaining
Output of iterating enum cases with CaseIterable
What is the output of this Swift code that iterates over enum cases using CaseIterable?
Swift
enum Direction: CaseIterable { case north, south, east, west } for direction in Direction.allCases { print(direction) }
Attempts:
2 left
💡 Hint
Remember that printing an enum case prints its name by default.
✗ Incorrect
The CaseIterable protocol provides the allCases collection. Iterating over it and printing each case prints the case name as a string, each on its own line.
🧠 Conceptual
intermediate1:00remaining
Why use CaseIterable with enums?
Why is the CaseIterable protocol useful when working with enums in Swift?
Attempts:
2 left
💡 Hint
Think about how you can get all enum cases without manually listing them.
✗ Incorrect
CaseIterable automatically synthesizes an allCases property that lists all enum cases, making iteration easy.
🔧 Debug
advanced2:00remaining
Fix the error when iterating enum without CaseIterable
This code tries to iterate over enum cases but causes an error. Which option fixes the error?
Swift
enum Color { case red, green, blue } for color in Color.allCases { print(color) }
Attempts:
2 left
💡 Hint
The error is because 'allCases' is not available without a protocol conformance.
✗ Incorrect
The allCases property is synthesized only if the enum conforms to CaseIterable.
📝 Syntax
advanced1:30remaining
Correct syntax for custom allCases implementation
Which option correctly implements a custom allCases property for an enum conforming to CaseIterable?
Swift
enum Fruit: CaseIterable { case apple, banana, cherry // custom allCases implementation }
Attempts:
2 left
💡 Hint
The allCases property must be static and return an array of enum cases.
✗ Incorrect
CaseIterable requires a static property named allCases returning a collection of all cases.
🚀 Application
expert1:00remaining
Count enum cases using CaseIterable
Given this enum, what is the value of 'count' after the code runs?
Swift
enum Status: CaseIterable { case pending, approved, rejected, cancelled } let count = Status.allCases.count
Attempts:
2 left
💡 Hint
Count returns the number of elements in the allCases collection.
✗ Incorrect
The enum has 4 cases, so allCases.count is 4.