What if missing just one case could crash your app? Swift's exhaustive switch saves you from that nightmare!
Why Switch must be exhaustive in Swift? - Purpose & Use Cases
Imagine you have a list of all possible fruits, and you want to write code that does something different for each fruit. You try to write a simple switch statement but forget to cover some fruits.
When you miss some fruits, your program might crash or behave unpredictably. You have to remember every single fruit manually, which is tiring and easy to forget. This leads to bugs and wasted time fixing them.
Swift's switch must be exhaustive, meaning you have to cover all possible cases or provide a default. This forces you to think about every option, making your code safer and more reliable.
switch fruit {
case "apple":
print("Apple selected")
// forgot other fruits
}switch fruit {
case "apple":
print("Apple selected")
case "banana":
print("Banana selected")
case "orange":
print("Orange selected")
default:
print("Unknown fruit")
}This ensures your program handles every possible case, preventing unexpected crashes and making your code bulletproof.
Think of a vending machine that must respond correctly to every button press. Exhaustive switches guarantee it never ignores a button, so customers always get what they expect.
Exhaustive switches prevent missing cases and bugs.
They force you to handle all possibilities or provide a fallback.
This leads to safer, more predictable programs.