๐ŸŽ“ A1Learner
๐Ÿ”

Swift Switch

A switch statement matches a value against a list of cases. The case that matches runs its own block of code.

Matching single values

Each case holds one value to compare against the stored number. The matching case prints its line and the other cases stay unused.

let day = 3
switch day {
case 1:
    print("Monday")
case 2:
    print("Tuesday")
case 3:
    print("Wednesday")
default:
    print("Later")
}

Several values in one case

Commas let one case hold two values on the same line. Either value runs the same block.

let score = 2
switch score {
case 1, 2:
    print("low")
case 3:
    print("high")
default:
    print("other")
}

Matching strings

Cases can hold strings as well as numbers. The stored string must match a case word for word.

let light = "green"
switch light {
case "red":
    print("stop")
case "green":
    print("go")
default:
    print("wait")
}

When nothing matches

No case holds the stored value in this switch. The default block runs instead of a case block.

let grade = "X"
switch grade {
case "A":
    print("top")
case "B":
    print("good")
default:
    print("ungraded")
}

Example

let month = 12
switch month {
case 1:
    print("January")
case 12:
    print("December")
default:
    print("Another month")
}

Key points

  • Use switch with the value to match and one case per choice.
  • Write several values in one case by separating them with commas.
  • A case can match a string value in quotes.
  • Use default for the block that runs when no case matches.
  • A case runs only its own block and execution does not fall into the next case.

In this example, month holds 12. The switch compares 12 with the first case and finds no match. The second case holds 12, so the program prints December. The default block stays unused because a case matched.

Note

A switch needs a default case when the cases do not cover every possible value.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Swift Compiler

Exercise

A switch on the number 5 has cases holding 1 and 5, plus a default. Which block runs?