Lesson 16Control Flow

While Loops

Loop While Condition is True

The while loop keeps running as long as a condition is true. Use it when you don't know how many times you need to loop!

Basic Syntax

while condition {
    // code to repeat
    // update condition
}

While vs For-In

Use While When:

  • Unknown number of iterations
  • Waiting for a condition
  • User input/events
  • Game loops

Use For-In When:

  • Known number of iterations
  • Looping through collections
  • Counting up/down
  • Processing each item

Common Use Cases

🎮

Game Loops

Play until game over

🔐

Login Attempts

Try until success

🔍

Search

Look until found

Warning: Infinite Loops!

Be careful!

  • Always update the condition inside the loop
  • Make sure the condition can become false
  • An infinite loop will crash your program!
main.swift
// Basic while loop
var count = 5

while count > 0 {
    print("Countdown: \(count)")
    count -= 1
}
print("Blast off!")

// Game example - rolling until you get 6
var diceRoll = 0

while diceRoll != 6 {
    diceRoll = Int.random(in: 1...6)
    print("You rolled: \(diceRoll)")
}
print("You got a 6! You win!")

// Summing numbers until limit
var sum = 0
var number = 1

while sum < 100 {
    sum += number
    print("Added \(number), sum is now \(sum)")
    number += 1
}
print("Final sum: \(sum)")

// Password attempt example
var attempts = 0
let maxAttempts = 3
var loggedIn = false

while attempts < maxAttempts && !loggedIn {
    attempts += 1
    let correctPassword = (attempts == 2) // Simulate correct on 2nd try

    if correctPassword {
        loggedIn = true
        print("Login successful!")
    } else {
        print("Wrong password. Attempt \(attempts) of \(maxAttempts)")
    }
}

if !loggedIn {
    print("Account locked!")
}

// Finding first even number
let numbers = [1, 3, 5, 8, 9, 11]
var index = 0

while index < numbers.count {
    if numbers[index] % 2 == 0 {
        print("First even number: \(numbers[index])")
        break
    }
    index += 1
}

Try It Yourself!

Create a guessing game: generate a random number 1-10, and use a while loop to let the user guess until they get it right!