0
0
Swiftprogramming~5 mins

Switch must be exhaustive in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does it mean for a switch statement to be exhaustive in Swift?
It means the switch must cover all possible cases of the value being checked, so no case is left unhandled.
Click to reveal answer
beginner
Why does Swift require switch statements to be exhaustive?
To ensure safety by forcing the programmer to handle every possible value, preventing unexpected behavior at runtime.
Click to reveal answer
beginner
How can you make a switch statement exhaustive when you don't want to handle all cases explicitly?
You can add a default case to catch all remaining values.
Click to reveal answer
intermediate
Given an enum with 3 cases, what happens if you write a switch statement that only handles 2 cases without a default?
The code will not compile because the switch is not exhaustive; the missing case must be handled or a default added.
Click to reveal answer
intermediate
Can switch statements on non-enum types be exhaustive in Swift?
Yes, but only by using a default case because non-enum types can have many values.
Click to reveal answer
What keyword can you use to make a switch statement exhaustive without listing all cases?
Adefault
Belse
Ccatch
Dfinal
If you have an enum with 4 cases, how many cases must your switch statement handle to be exhaustive?
AAll 4 or use default
BNone, switch is always exhaustive
COnly 1
DAt least 3
What happens if a switch statement on an enum is not exhaustive in Swift?
AIt compiles but crashes at runtime
BIt compiles with a warning
CIt does not compile
DIt runs but skips missing cases
Can you omit the default case if your switch covers all enum cases?
ANo, default is always required
BYes, if all cases are covered
COnly if enum has less than 3 cases
DOnly for integer types
Why might you prefer to list all enum cases explicitly instead of using default?
ATo avoid runtime errors
BTo make code shorter
CTo improve performance
DTo get compiler errors if new cases are added later
Explain what it means for a switch statement to be exhaustive in Swift and why it is important.
Think about how Swift prevents missing cases in switch.
You got /4 concepts.
    Describe how you can make a switch statement exhaustive when working with enums and when working with other types.
    Consider differences between enums and other types.
    You got /3 concepts.