Swift Switch

Master conditional logic with Swift switch statements

🔀 What is Swift Switch?

Swift switch statements provide a powerful way to compare values against multiple patterns. They're safer and more expressive than traditional if-else chains, supporting pattern matching and value binding.


// Simple switch example
let grade = "A"
switch grade {
case "A":
    print("Excellent!")
case "B":
    print("Good job!")
default:
    print("Keep trying!")
}
                                    

Output:

Excellent!

Switch Statement Features

🎯

Exact Matching

Match specific values precisely

switch number {
case 1: print("One")
case 2: print("Two")
default: print("Other")
}
📊

Range Matching

Match ranges of values

switch score {
case 90...100: print("A")
case 80..<90: print("B")
default: print("C")
}
🔗

Multiple Values

Match multiple values in one case

switch day {
case "Sat", "Sun":
    print("Weekend!")
default:
    print("Weekday")
}
🎨

Tuple Matching

Match complex data structures

switch (x, y) {
case (0, 0): print("Origin")
case (_, 0): print("X-axis")
default: print("Other")
}

🔹 Basic Switch Syntax

Every switch statement must be exhaustive - covering all possible values:

let weather = "sunny"

switch weather {
case "sunny":
    print("Wear sunglasses! ☀️")
case "rainy":
    print("Take an umbrella! 🌧️")
case "cloudy":
    print("Perfect for a walk! ☁️")
default:
    print("Check the weather app!")
}

Output:

Wear sunglasses! ☀️

🔹 Switch with Ranges

Use ranges to match intervals of values:

let temperature = 75

switch temperature {
case ...32:
    print("Freezing! 🥶")
case 33...60:
    print("Cold 🧥")
case 61...80:
    print("Perfect! 😊")
case 81...:
    print("Hot! 🔥")
default:
    break // This will never execute
}

Output:

Perfect! 😊

🔹 Switch with Where Clause

Add conditions to cases using where:

let point = (3, 4)

switch point {
case let (x, y) where x == y:
    print("On the diagonal")
case let (x, y) where x > 0 && y > 0:
    print("In first quadrant: (\(x), \(y))")
case let (x, y):
    print("Point at (\(x), \(y))")
}

Output:

In first quadrant: (3, 4)

🧠 Test Your Knowledge

What happens if you don't include a default case in a Swift switch?