Swift Switch Statement

A switch statement checks a value against multiple possible matches and runs the code for the matching case. It replaces long chains of if-else if blocks when you have many specific values to check.

The TV Remote Analogy


┌──────────────────────────────────────────────┐
│  Pressing a button on a TV remote            │
│                                              │
│  Button 1 pressed → Switch to Channel 1      │
│  Button 2 pressed → Switch to Channel 2      │
│  Volume Up        → Increase volume          │
│  Mute             → Silence audio            │
│  Anything else    → Do nothing               │
│                                              │
│  Each button maps to one specific action.    │
└──────────────────────────────────────────────┘

Basic Switch Syntax

let day = "Monday"

switch day {
case "Monday":
    print("Start of the work week.")
case "Friday":
    print("Last day before weekend!")
case "Saturday", "Sunday":
    print("Weekend time!")
default:
    print("A regular weekday.")
}
// Output: Start of the work week.

Swift matches day against each case. When a match is found, that block runs. The default case handles anything that does not match a specific case.

No Fall-Through by Default


┌──────────────────────────────────────────────────┐
│  In C/Java (other languages):                    │
│  case 1: runs, then falls into case 2 too!       │
│                                                  │
│  In Swift:                                       │
│  case 1: runs, then STOPS. No fall-through.      │
│                                                  │
│  Swift is safer — each case is independent.      │
└──────────────────────────────────────────────────┘

Matching Numbers

let score = 85

switch score {
case 90...100:
    print("Grade A")
case 75...89:
    print("Grade B")
case 60...74:
    print("Grade C")
default:
    print("Grade F")
}
// Output: Grade B

Switch cases work with ranges too. The range 75...89 matches any number from 75 to 89, including both ends.

Matching Tuples

let point = (3, 0)

switch point {
case (0, 0):
    print("Origin")
case (_, 0):
    print("On the X-axis")
case (0, _):
    print("On the Y-axis")
default:
    print("Somewhere else")
}
// Output: On the X-axis

A tuple is two values grouped together. The underscore _ means "any value here". This lets you match partial patterns.

Value Binding in Cases

let speed = 120

switch speed {
case let s where s > 100:
    print("Speeding at \(s) km/h")
case let s where s == 0:
    print("Parked")
default:
    print("Normal speed")
}
// Output: Speeding at 120 km/h

Value binding with let captures the matched value and gives it a name. The where clause adds an extra condition to the case.

Using fallthrough Intentionally

let number = 3

switch number {
case 3:
    print("Three")
    fallthrough
case 4:
    print("Four (fell through)")
default:
    print("Other")
}
// Three
// Four (fell through)

When you explicitly need fall-through behavior, add the fallthrough keyword. Swift will continue into the next case without checking its condition.

Switch vs if-else – When to Use Which


┌──────────────────────────────────────────────────┐
│  Use switch when:                                │
│  - Checking one value against many known options │
│  - Matching ranges or patterns                   │
│                                                  │
│  Use if-else when:                               │
│  - Checking complex or unrelated conditions      │
│  - Combining multiple variables per check        │
└──────────────────────────────────────────────────┘

Leave a Comment

Your email address will not be published. Required fields are marked *