Lesson 13Control Flow

Else-If Chain

Multiple Conditions

When you have more than two possibilities, use else if to check multiple conditions in sequence!

Basic Syntax

if condition1 {
    // first option
} else if condition2 {
    // second option
} else if condition3 {
    // third option
} else {
    // default option
}

How It Works

  1. Swift checks the first condition
  2. If true, runs that code and skips the rest
  3. If false, moves to the next condition
  4. If nothing matches, runs the else block

Grade Example

A

90-100

B

80-89

C

70-79

D

60-69

F

0-59

Key Points

  • Order matters! Check specific conditions first
  • Only ONE block runs (the first match)
  • The final else catches everything else
  • You can have as many else if as needed
main.swift
// Grade calculator with else-if chain
let score = 85

if score >= 90 {
    print("Grade: A - Excellent!")
} else if score >= 80 {
    print("Grade: B - Great job!")
} else if score >= 70 {
    print("Grade: C - Good!")
} else if score >= 60 {
    print("Grade: D - Passed!")
} else {
    print("Grade: F - Try again!")
}

// Weather outfit picker
let temperature = 15

if temperature >= 30 {
    print("Wear shorts and t-shirt!")
} else if temperature >= 20 {
    print("Wear light clothes!")
} else if temperature >= 10 {
    print("Wear a jacket!")
} else if temperature >= 0 {
    print("Wear a warm coat!")
} else {
    print("Stay inside, it's freezing!")
}

// Age-based ticket price
let age = 12
var ticketPrice: Int

if age < 3 {
    ticketPrice = 0
    print("Free admission!")
} else if age < 12 {
    ticketPrice = 5
    print("Child ticket: $\(ticketPrice)")
} else if age < 65 {
    ticketPrice = 10
    print("Adult ticket: $\(ticketPrice)")
} else {
    ticketPrice = 7
    print("Senior ticket: $\(ticketPrice)")
}

// Time of day greeting
let hour = 14

if hour < 12 {
    print("Good morning!")
} else if hour < 17 {
    print("Good afternoon!")
} else if hour < 21 {
    print("Good evening!")
} else {
    print("Good night!")
}

Try It Yourself!

Create an else-if chain that determines what activity to do based on the weather: sunny, cloudy, rainy, or snowy!