AI Workshop: learn to build apps with AI →
Control Flow: Switch Statements

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


This tutorial belongs to the Swift series

Switch statements are a handy way to create a conditional with multiple options:

var name = "Roger"

switch name {
case "Roger":
    print("Hello, Mr. Roger!")
default: 
    print("Hello, \(name)")
}

When the code of a case ends, the switch exits automatically.

A switch in Swift must cover all cases. If the tagname in this example—can be any string value, you must add a default case.

Otherwise with an enumeration, you can simply list all the options:

enum Animal {
    case dog
    case cat
}

var animal: Animal = .dog

switch animal {
case .dog:
    print("Hello, dog!")
case .cat:
    print("Hello, cat!")
}

A case can be a Range:

var age = 20

switch age {
case 0..<18:
    print("You can't drive!")
default: 
    print("You can drive")
}

Lessons in this unit:

0: Introduction
1: If Statements
2: ▶︎ Switch Statements
3: Ternary Operator
4: For-In Loops
5: While Loops
6: Repeat-While Loops
7: Control Transfer Statements