Swift
Beginner
1 min read
Conditionals and Loops
Example
// if / else if / else
let temp = 72
if temp > 90 {
print("Hot")
} else if temp > 70 {
print("Warm")
} else {
print("Cool")
}
// guard for early exit
func process(name: String?) {
guard let name = name, !name.isEmpty else {
print("Invalid name")
return
}
print("Processing: \(name)")
}
// switch - exhaustive, no fallthrough
let day = 3
switch day {
case 1: print("Monday")
case 2: print("Tuesday")
case 3...5: print("Mid-week")
case 6, 7: print("Weekend")
default: print("Unknown")
}
// for-in
for i in 1...5 { print(i) }
for i in stride(from: 0, through: 10, by: 2) { print(i) }
let names = ["Alice", "Bob", "Charlie"]
for (index, name) in names.enumerated() {
print("\(index): \(name)")
}
// while
var count = 0
while count < 5 { count += 1 }
// repeat-while (do-while equivalent)
repeat { count -= 1 } while count > 0