Control Flow: if, switch and Loops

IOS Development 10 min min read Updated: Nov 16, 2026 Beginner
Control Flow: if, switch and Loops
Beginner Topic 2 of 9

if and else

swift let temperature = 28 if temperature > 30 { print("Hot") } else if temperature > 20 { print("Warm") } else { print("Cool") }

Swift does not need brackets around the condition, but the curly braces are required.

switch: Powerful Matching

swift let grade = "B" switch grade { case "A": print("Excellent") case "B", "C": print("Good") default: print("Keep trying") } let score = 72 switch score { case 90...100: print("A") case 70..<90: print("B") case ..<70: print("C") default: break }
Swift switch is special: It must be exhaustive (cover all cases, or use default), and it does not fall through to the next case, so you do not need break.

for-in Loops

swift for i in 1...3 { print("Round \(i)") } let fruits = ["apple", "banana", "mango"] for fruit in fruits { print(fruit) } for (index, fruit) in fruits.enumerated() { print("\(index): \(fruit)") } for _ in 1...3 { print("Hi") } // underscore: we do not need the value

while and repeat-while

swift var n = 3 while n > 0 { print(n) n -= 1 } repeat { print("Runs at least once") } while false

break, continue and where

swift for i in 1...10 { if i == 3 { continue } // skip 3 if i == 6 { break } // stop at 6 print(i) } for i in 1...10 where i % 2 == 0 { print(i) // only even numbers }

guard: Exit Early

guard checks a condition and leaves the function if it is not true. It keeps your code flat and readable.

swift func greet(name: String?) { guard let name = name, !name.isEmpty else { print("No name given") return } print("Hello, \(name)!") // name is safely available here }

if and switch as Expressions (Swift 5.9+)

swift let label = if score >= 50 { "Pass" } else { "Fail" } let message = switch score { case 90...: "Excellent" case 50..<90: "Good" default: "Try again" }

Conclusion

Swift's control flow is clean and safe. Learn switch with ranges and guard for early exits.

Quick Summary: Use if, switch (exhaustive, no fall-through), for-in with ranges, while and guard.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators