A switch statement helps you check a value against many possibilities easily. It makes your code cleaner and easier to read than many if-else checks.
0
0
Switch statement power in Swift
Introduction
When you want to choose different actions based on a single value.
When you have many conditions to check and want clear, organized code.
When you want to match values, ranges, or even complex patterns.
When you want to handle different cases with specific code blocks.
When you want to avoid writing many if-else statements.
Syntax
Swift
switch value { case pattern1: // code to run case pattern2, pattern3: // code to run case let x where x > 10: // code to run default: // code to run if no case matches }
The switch checks the value against each case in order.
The default case runs if no other case matches. It is required unless all cases are covered.
Examples
Simple switch checking exact values.
Swift
let number = 3 switch number { case 1: print("One") case 2: print("Two") case 3: print("Three") default: print("Other number") }
Multiple values in one case separated by commas.
Swift
let letter = "a" switch letter { case "a", "e", "i", "o", "u": print("Vowel") default: print("Consonant") }
Using ranges to match age groups.
Swift
let age = 25 switch age { case 0..<13: print("Child") case 13..<20: print("Teenager") case 20..<65: print("Adult") default: print("Senior") }
Matching tuples with value binding to variables.
Swift
let point = (1, 2) switch point { case (0, 0): print("Origin") case (let x, 0): print("On the x-axis at \(x)") case (0, let y): print("On the y-axis at \(y)") case let (x, y): print("At point (\(x), \(y))") }
Sample Program
This program checks the weather and suggests what to do. It uses a switch to pick the right message.
Swift
let weather = "rainy" switch weather { case "sunny": print("Wear sunglasses") case "rainy": print("Take an umbrella") case "snowy": print("Wear a coat") default: print("Check the weather report") }
OutputSuccess
Important Notes
Each case in Swift switch must be exhaustive or you must provide a default case.
Switch cases do not fall through by default, so you don't need break statements.
You can use where clauses to add extra conditions to cases.
Summary
Switch statements let you check a value against many cases clearly.
They support matching exact values, multiple values, ranges, and patterns.
Switch makes your code easier to read and maintain compared to many if-else statements.