Control Flow
Control flow lets you make decisions and repeat actions in your programs.
If Statementsâ
Make decisions based on conditions:
let age = 18
if age >= 18 {
print("You are an adult")
} else {
print("You are a minor")
}
Multiple Conditionsâ
let score = 85
if score >= 90 {
print("Grade: A")
} else if score >= 80 {
print("Grade: B")
} else if score >= 70 {
print("Grade: C")
} else {
print("Grade: F")
}
Loopsâ
For Loopâ
Count through a range:
for i in 1..5 {
print(i)
}
// Output: 1 2 3 4 5
While Loopâ
Repeat while a condition is true:
let count = 0
while count < 3 {
print("Count: " + count)
count = count + 1
}
// Output: Count: 0 Count: 1 Count: 2
Loop Controlâ
for i in 1..10 {
if i == 3 {
continue // Skip this iteration
}
if i == 7 {
break // Exit the loop
}
print(i)
}
// Output: 1 2 4 5 6
When Statementsâ
When expressions provide powerful pattern matching:
let day = "Monday"
when day {
"Monday" => print("Start of work week"),
"Friday" => print("TGIF!"),
"Saturday" | "Sunday" => print("Weekend!"),
_ => print("Regular day"),
}
Matching Numbersâ
let number = 5
when number {
0 => print("Zero"),
1..10 => print("Single digit"),
10..100 => print("Double digit"),
_ => print("Large number"),
}
What's Next?â
- Functions - Organize your code
- Collections - Work with lists and data structures