0
0
Swiftprogramming~5 mins

Iterating enum cases with CaseIterable in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the CaseIterable protocol do in Swift enums?
It allows an enum to provide a collection of all its cases, so you can easily loop through them.
Click to reveal answer
beginner
How do you make an enum conform to CaseIterable?
Add CaseIterable after the enum name, like enum Direction: CaseIterable { ... }.
Click to reveal answer
beginner
How can you access all cases of a CaseIterable enum?
Use the static property allCases, for example: Direction.allCases returns a collection of all cases.
Click to reveal answer
intermediate
What type is allCases in a CaseIterable enum?
It is a collection (usually an array) of all enum cases, with type [EnumName].
Click to reveal answer
beginner
Why is CaseIterable useful when working with enums?
It lets you easily loop over all enum cases without manually listing them, which saves time and reduces errors.
Click to reveal answer
How do you declare an enum named Color that supports iterating all its cases?
Aenum Color: CaseIterable { case red, green, blue }
Benum Color { case red, green, blue }
Cenum Color: Iterable { case red, green, blue }
Denum Color: IterableCase { case red, green, blue }
What does Color.allCases return if Color conforms to CaseIterable?
AAn array of all Color enum cases
BA single Color case
CA string listing all cases
DAn integer count of cases
Which of these is a valid way to loop through all cases of a CaseIterable enum Direction?
Afor dir in Direction.cases { print(dir) }
Bfor dir in Direction { print(dir) }
Cfor dir in Direction.allCases { print(dir) }
Dfor dir in Direction.iterate() { print(dir) }
If you add a new case to a CaseIterable enum, what happens to allCases?
AIt excludes the new case
BYou must update <code>allCases</code> manually
CIt breaks the code
DIt automatically includes the new case
Can enums with associated values conform to CaseIterable?
AYes, all enums can conform
BNo, only enums without associated values can conform
COnly if associated values are Int
DOnly if associated values are String
Explain how to use CaseIterable to loop through all cases of an enum in Swift.
Think about how you get all cases and then loop over them.
You got /3 concepts.
    What are the benefits of making an enum conform to CaseIterable?
    Consider how it helps when you want to do something with every case.
    You got /4 concepts.