Lesson 17Control Flow
Repeat-While
Do First, Check Later
The repeat-while loop runs the code first, then checks the condition. It always runs at least once!
Basic Syntax
repeat {
// code to run
} while conditionWhile vs Repeat-While
while
Check → Run
- Checks condition first
- May run 0 times
repeat-while
Run → Check
- Runs code first
- Runs at least 1 time
When to Use Repeat-While
📋
Menu Systems
Show menu at least once
✅
Input Validation
Get input, then validate
🎲
Games
Roll dice at least once
🔄
Retry Logic
Try at least once
Key Difference
Remember: repeat-while is called do-while in other languages (C, Java, JavaScript). Swift uses repeat to avoid confusion with the do keyword used for error handling!
main.swift
// Basic repeat-while loop
var count = 0
repeat {
print("Count: \(count)")
count += 1
} while count < 5
// Always runs at least once!
var number = 10
repeat {
print("This runs even though number is already 10!")
} while number < 5
// Menu selection example
var choice = 0
repeat {
print("Menu:")
print("1. Play Game")
print("2. Settings")
print("3. Exit")
choice = Int.random(in: 1...3) // Simulate user input
print("You selected: \(choice)")
switch choice {
case 1:
print("Starting game...")
case 2:
print("Opening settings...")
case 3:
print("Goodbye!")
default:
print("Invalid choice")
}
} while choice != 3
// Dice game - roll until you get 6
var roll: Int
repeat {
roll = Int.random(in: 1...6)
print("You rolled: \(roll)")
} while roll != 6
print("You got 6! Game over!")
// Input validation simulation
var validInput = false
var attempts = 0
repeat {
attempts += 1
validInput = (attempts == 3) // Simulate valid on 3rd try
if !validInput {
print("Invalid input, try again...")
}
} while !validInput
print("Input accepted after \(attempts) attempts!")Try It Yourself!
Create a simple menu that shows options and keeps asking the user until they choose "Exit"!