The switch statement evaluates a value and compares it against several possible matching patterns.
It provides an alternative to using long, complex if...else if chains.
In Swift, switch statements are extremely powerful, safe, and versatile.
A switch statement consists of multiple case blocks. Swift will execute the block of code matching the first case that evaluates to true.
Every switch statement must be exhaustive, meaning it must cover every possible value. To ensure this, you usually provide a default case at the end.
let dayOfWeek = 3switch dayOfWeek { case 1: print("Monday") case 2: print("Tuesday") case 3: print("Wednesday") default: print("Other day") }
In languages like C, you must manually write break at the end of every case, otherwise, the code "falls through" to the next case automatically.
In Swift, switch statements do not fall through by default. As soon as the matching case finishes executing, the entire switch statement completes.
You don't need to write break!
One of the most powerful features of Swift's switch is its ability to check against ranges!
let score = 85switch score { case 0..<50: print("Fail") case 50..<80: print("Pass") case 80...100: print("Excellent") default: print("Invalid score") }
Do you need to write a 'break' statement at the end of every case in a Swift switch?