Module 5: Control Flow in Swift (Conditionals and Loops)
Control flow statements let you decide which parts of your code run and how many times they run. Swift provides powerful control flow structures such as conditionals (if, else, switch) and loops (for-in, while, repeat-while) to help you manage the execution path of your programs.
If and Else Statements
The if
statement executes a block of code only if a condition is true. You can add an else
block to run code when the condition is false.
let temperature = 30
if temperature > 25 {
print("It's a hot day!")
} else {
print("It's not that hot.")
}
Else If
Use else if
to check multiple conditions.
let score = 85
if score >= 90 {
print("Grade A")
} else if score >= 75 {
print("Grade B")
} else {
print("Grade C or below")
}
Switch Statement
The switch
statement is a more powerful alternative to multiple if-else statements, especially when checking against many values.
let day = "Tuesday"
switch day {
case "Monday":
print("Start of the week")
case "Tuesday":
print("Second day")
case "Wednesday", "Thursday":
print("Midweek days")
default:
print("Weekend or other day")
}
For-In Loop
The for-in
loop iterates over sequences such as arrays, ranges, or strings.
let fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits {
print(fruit)
}
While Loop
The while
loop repeats a block of code as long as a condition is true.
var count = 1
while count <= 5 {
print(count)
count += 1
}
Repeat-While Loop
This loop is similar to while
, but it executes the code block at least once before checking the condition.
var number = 1
repeat {
print(number)
number += 1
} while number <= 5
Control Transfer Statements
break
: Exits a loop or switch statement early.continue
: Skips the current loop iteration and moves to the next.fallthrough
: Forces execution to continue to the next case in a switch.
Example: Using Control Transfer
for i in 1...5 {
if i == 3 {
continue // skip 3
}
print(i)
}
Output: 1 2 4 5
Summary
- Use
if
,else if
, andelse
to make decisions. switch
is a clean way to check multiple values.- Loops (
for-in
,while
,repeat-while
) let you repeat code. - Control transfer statements manage loop execution flow.