switch compares one value with several cases and runs the matching case body.

Match a value

direction
switch_cases.swift
Replay: real traced execution (multi-file project)
let direction = "north"
var dx = 0
var dy = 0

switch direction {
case "north":
    dy = 1
case "east":
    dx = 1
default:
    dy = -1
}

print("direction=\(direction)")
print("move=\(dx),\(dy)")
let direction = "east"
var dx = 0
var dy = 0

switch direction {
case "north":
    dy = 1
case "east":
    dx = 1
default:
    dy = -1
}

print("direction=\(direction)")
print("move=\(dx),\(dy)")
let direction = "down"
var dx = 0
var dy = 0

switch direction {
case "north":
    dy = 1
case "east":
    dx = 1
default:
    dy = -1
}

print("direction=\(direction)")
print("move=\(dx),\(dy)")
  1. direction ← north, dx ← 0, dy ← 0

    1let direction→ north = "north"  //@direction="east", "down"2var dx→ 0 = 03var dy→ 0 = 0
  2. switch direction

    5switch directionnorth {6case "north":7    dy = 1
  3. dy ← 1

    5switch direction {6case "north":7    dy→ 1 = 18case "east":
  4. print("direction=\(direction)")

    14print("direction=\(directionnorth)")15print("move=\(dx0),\(dy1)")
    outputdirection=north
    move=0,1
  1. direction ← east, dx ← 0, dy ← 0

    1let direction→ east = "east"2var dx→ 0 = 03var dy→ 0 = 0
  2. switch direction

    5switch directioneast {6case "north":7    dy = 1
  3. dx ← 1

    7    dy = 18case "east":9    dx→ 1 = 110default:
  4. print("direction=\(direction)")

    14print("direction=\(directioneast)")15print("move=\(dx1),\(dy0)")
    outputdirection=east
    move=1,0
  1. direction ← down, dx ← 0, dy ← 0

    1let direction→ down = "down"2var dx→ 0 = 03var dy→ 0 = 0
  2. switch direction

    5switch directiondown {6case "north":7    dy = 1
  3. dy ← -1

    9    dx = 110default:11    dy→ -1 = -112}
  4. print("direction=\(direction)")

    14print("direction=\(directiondown)")15print("move=\(dx0),\(dy-1)")
    outputdirection=down
    move=0,-1

Match the Direction

  1. direction starts as north.
  2. switch checks the direction cases.
  3. case "north" matches.
  4. dy becomes 1, so the move prints 0,1. | Direction | Case used | Move | | --- | --- | --- | | north | case "north" | 0,1 | | east | case "east" | 1,0 | | down | default | 0,-1 |
switch A `switch` keeps multi-way decisions readable. The `default` case handles values that do not match an earlier case.

Exercise: switch_cases.swift

Use switch to map a direction to the correct dx,dy move