Swift: Control Flow
What you will learn
Conditionals, Swift's powerful switch statement, and the for-in loop with ranges.
if / else if / else
let score = 85
if score >= 90 {
print("A")
} else if score >= 80 {
print("B")
} else {
print("F")
}
Conditions must be boolean — no truthy/falsy coercion.
For-in with ranges
for i in 1...5 {
print(i) // 1, 2, 3, 4, 5
}
for i in 1..<5 {
print(i) // 1, 2, 3, 4 (half-open, excludes 5)
}
for char in "Hello" {
print(char) // H e l l o
}
... is the closed range operator (includes both ends). ..< is the half-open range operator (excludes the last value).
Switch statement
Swift's switch is exhaustive — every possible value must be covered:
let day = "Monday"
switch day {
case "Monday":
print("Start of week")
case "Friday":
print("Almost weekend")
default:
print("Midweek")
}
No break needed — Swift's switch does not fall through. Use fallthrough explicitly if you want C-style fallthrough.
While loops
var i = 0
while i < 5 {
print(i)
i += 1
}
Guard statement (Swift's unique early exit)
guard is like an if that requires an else to exit the current scope. It keeps the "happy path" unindented:
func greet(person: [String: String]) {
guard let name = person["name"] else {
return // name was nil — exit early
}
print("Hello, \(name)!") // happy path
}
Common mistakes
- Forgetting a
defaultcase inswitch— Swift requires exhaustive coverage - Using
...when you meant..<— off-by-one bugs are common with ranges - Expecting
ifto accept non-boolean values — Swift only accepts trueBoolexpressions
Quick check below!