Recall & Review
beginner
What is an enum in Swift?
An enum (short for enumeration) is a type that groups related values under a common name. It helps organize code by defining a set of possible cases.
Click to reveal answer
beginner
How does switch pattern matching work with enums in Swift?
Switch pattern matching lets you check which enum case a value matches and run code for that case. It can also extract associated values if the enum has them.
Click to reveal answer
intermediate
What happens if you don’t cover all enum cases in a switch statement?
Swift requires all enum cases to be handled in a switch. If not, you must add a default case or the code won’t compile.
Click to reveal answer
intermediate
How do you extract associated values from an enum case in a switch?
Use case pattern matching with let or var to bind the associated values to variables inside the switch case.Click to reveal answer
beginner
Example: What does this code print?
<pre>enum Direction { case north, south, east, west }
let dir = Direction.east
switch dir {
case .north: print("Up")
case .south: print("Down")
case .east: print("Right")
case .west: print("Left")
}</pre>It prints "Right" because the value dir is .east and the switch matches that case.
Click to reveal answer
What keyword is used to define an enum in Swift?
✗ Incorrect
The keyword 'enum' is used to define an enumeration in Swift.
What must a switch statement do when matching an enum?
✗ Incorrect
Swift requires switch statements to be exhaustive, meaning all enum cases must be handled or a default case must be provided.
How do you access associated values in a switch case?
✗ Incorrect
You use let or var inside the case pattern to extract associated values from an enum case.
Which of these is a valid enum case pattern in a switch?
✗ Incorrect
Inside a switch on an enum, you use the shorthand '.caseName' to match cases.
What will happen if you forget to handle an enum case in a switch without a default?
✗ Incorrect
Swift enforces exhaustiveness in switch statements on enums, so missing cases cause a compile-time error.
Explain how to use switch pattern matching with enums in Swift, including handling associated values.
Think about how you check each case and get values out if needed.
You got /4 concepts.
Describe why Swift requires switch statements on enums to be exhaustive and how you can satisfy this requirement.
Consider safety and completeness in your code.
You got /3 concepts.