0
0
Swiftprogramming~20 mins

Iterating enum cases with CaseIterable in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
CaseIterable Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
1: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)
}
ADirection.north\nDirection.south\nDirection.east\nDirection.west
B0\n1\n2\n3
Cnorth\nsouth\neast\nwest
Dnorth south east west
Attempts:
2 left
💡 Hint
Remember that printing an enum case prints its name by default.
🧠 Conceptual
intermediate
1:00remaining
Why use CaseIterable with enums?
Why is the CaseIterable protocol useful when working with enums in Swift?
AIt enables enums to inherit from other enums.
BIt automatically provides a collection of all enum cases for iteration.
CIt allows enums to have stored properties.
DIt makes enums conform to Codable automatically.
Attempts:
2 left
💡 Hint
Think about how you can get all enum cases without manually listing them.
🔧 Debug
advanced
2: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)
}
AAdd raw values to the enum cases.
BChange 'Color.allCases' to 'Color.cases'.
CReplace 'for' loop with 'while' loop.
DAdd ': CaseIterable' to the enum declaration.
Attempts:
2 left
💡 Hint
The error is because 'allCases' is not available without a protocol conformance.
📝 Syntax
advanced
1: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
}
Astatic var allCases: [Fruit] { return [.apple, .banana, .cherry] }
Bvar allCases: [Fruit] { return [.apple, .banana, .cherry] }
Cstatic func allCases() -> [Fruit] { return [.apple, .banana, .cherry] }
Dlet allCases = [.apple, .banana, .cherry]
Attempts:
2 left
💡 Hint
The allCases property must be static and return an array of enum cases.
🚀 Application
expert
1: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
A4
B3
CCompilation error
D0
Attempts:
2 left
💡 Hint
Count returns the number of elements in the allCases collection.