Swift requires switch statements to cover all possible cases. This helps avoid mistakes by making sure you handle every option.
0
0
Switch must be exhaustive in Swift
Introduction
When you want to check all possible values of an enum.
When you want to make sure no case is forgotten in decision making.
When you want your code to be safer and easier to maintain.
When you want the compiler to warn you if a new case is added but not handled.
When you want to handle different types of input clearly and completely.
Syntax
Swift
switch value { case pattern1: // code case pattern2: // code // ... all cases must be covered }
All possible cases must be covered, either explicitly or with a default case.
If you use an enum, the switch must handle every enum case or include default.
Examples
This switch covers all enum cases, so it is exhaustive.
Swift
enum Direction { case north, south, east, west } let dir = Direction.north switch dir { case .north: print("Going north") case .south: print("Going south") case .east: print("Going east") case .west: print("Going west") }
Using
default covers all other values, making the switch exhaustive.Swift
let number = 3 switch number { case 1: print("One") case 2: print("Two") default: print("Other number") }
Sample Program
This program uses a switch on an enum with all cases handled. It prints the correct action for each light color.
Swift
enum Light { case red, yellow, green } func action(for light: Light) { switch light { case .red: print("Stop") case .yellow: print("Get ready") case .green: print("Go") } } action(for: .red) action(for: .yellow) action(for: .green)
OutputSuccess
Important Notes
If you forget a case in a switch on an enum, Swift will give a compile error.
You can use default to cover all other cases, but it's better to list all enum cases explicitly for clarity.
Exhaustive switches help catch errors early and make your code safer.
Summary
Swift switch statements must cover all possible cases.
Use explicit cases or a default to be exhaustive.
This rule helps prevent bugs and makes code easier to understand.