Lesson 14Control Flow

Switch Statement

Cleaner Multiple Choices

When you have many possible values to check, switch is cleaner than long if-else chains!

Basic Syntax

switch value {
case option1:
    // code
case option2:
    // code
default:
    // fallback
}

Switch Features

Multiple Values

case 1, 2, 3:

Match any of these

Ranges

case 1...10:

Match a range of values

Where Clause

case let x where x > 0:

Add extra conditions

Default

default:

Catches all other cases

Switch vs If-Else

Use Switch When:

  • Checking one value against many options
  • Each option has simple, distinct values
  • You want cleaner, more readable code

Use If-Else When:

  • Checking different conditions
  • Complex boolean expressions
  • Comparing multiple variables

Key Points

  • Switch must be exhaustive (cover all cases)
  • No fall-through by default (unlike C/Java)
  • Use default for uncovered cases
  • Each case must have at least one statement
main.swift
// Basic switch statement
let day = 3

switch day {
case 1:
    print("Monday")
case 2:
    print("Tuesday")
case 3:
    print("Wednesday")
case 4:
    print("Thursday")
case 5:
    print("Friday")
case 6, 7:
    print("Weekend!")
default:
    print("Invalid day")
}

// Switch with strings
let animal = "dog"

switch animal {
case "dog":
    print("Woof!")
case "cat":
    print("Meow!")
case "cow":
    print("Moo!")
default:
    print("Unknown animal")
}

// Switch with ranges
let score = 85

switch score {
case 90...100:
    print("Grade A")
case 80..<90:
    print("Grade B")
case 70..<80:
    print("Grade C")
case 60..<70:
    print("Grade D")
case 0..<60:
    print("Grade F")
default:
    print("Invalid score")
}

// Switch with where clause
let point = (2, 0)

switch point {
case (let x, 0):
    print("On x-axis at \(x)")
case (0, let y):
    print("On y-axis at \(y)")
case let (x, y) where x == y:
    print("On diagonal at \(x)")
default:
    print("Somewhere else")
}

// Compound cases
let letter = "a"

switch letter {
case "a", "e", "i", "o", "u":
    print("Vowel")
default:
    print("Consonant")
}

Try It Yourself!

Create a switch statement that prints the month name for a given month number (1-12)!