Bird
0
0

Given this enum and switch, how can you make the switch exhaustive without listing all cases explicitly?

hard📝 Application Q15 of 15
Swift - Control Flow
Given this enum and switch, how can you make the switch exhaustive without listing all cases explicitly?
enum Status { case success, failure, unknown }
let currentStatus = Status.unknown
switch currentStatus {
 case .success: print("Success")
 case .failure: print("Failure")
}
AAdd a <code>default</code> case to handle all other values.
BRemove the switch and use if-else instead.
CAdd a case for .unknown explicitly.
DChange enum to have only two cases.
Step-by-Step Solution
Solution:
  1. Step 1: Understand the problem with current switch

    The switch handles .success and .failure but misses .unknown, so it's not exhaustive.
  2. Step 2: Find a way to cover missing cases without listing all explicitly

    Adding a default case covers any cases not explicitly handled, making the switch exhaustive.
  3. Final Answer:

    Add a default case to handle all other values. -> Option A
  4. Quick Check:

    Use default to cover missing cases = A [OK]
Quick Trick: Use default to cover all unlisted cases quickly [OK]
Common Mistakes:
  • Thinking you must list every case explicitly
  • Removing switch instead of fixing it
  • Changing enum just to fix switch

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes