Consider the following Swift code with an exhaustive switch on an enum. What will it print?
enum Direction { case north, south, east, west } let dir = Direction.east switch dir { case .north: print("Going north") case .south: print("Going south") case .east: print("Going east") case .west: print("Going west") }
Check if all enum cases are covered in the switch.
The switch covers all cases of the enum Direction, so it is exhaustive. The variable dir is .east, so it prints "Going east".
What error will this Swift code produce?
enum Color { case red, green, blue } let c = Color.green switch c { case .red: print("Red") case .blue: print("Blue") }
Swift requires switches on enums to cover all cases or have a default.
The switch does not cover the .green case and has no default, so the compiler reports an error that the switch is not exhaustive.
Why does Swift require switches on enums to be exhaustive?
Think about safety and predictability in code.
Requiring exhaustive switches ensures the programmer handles every possible case, avoiding bugs from unhandled cases at runtime.
Given the enum below, which switch statement is exhaustive and compiles without error?
enum Status { case success case failure case unknown }
Check if all cases are covered or if a default is used.
Option B covers all three cases explicitly, so it is exhaustive. Options A and B miss the .unknown case.
Given this enum with associated values, how many cases must a switch handle to be exhaustive?
enum Result { case success(Int) case failure(String) case pending }
Remember each enum case counts separately regardless of associated values.
All three cases must be handled explicitly or with a default. Associated values do not increase the number of cases, but each case is distinct.