Swift: Control flow – code examples
if / else if / else
Use case: Reacting differently, e.g. calculating grades or price tiers.
let punkte = 73
if punkte >= 90 {
print("excellent")
} else if punkte >= 70 {
print("good")
} else {
print("needs improvement")
}No parentheses around the condition, but braces around the block are mandatory. For many cases, switch with ranges (90...100) is clearer.
for-in loop
Use case: Processing every element of a list or repeating n times.
for i in 0..<3 {
print("Round", i)
}
for frucht in ["Apple", "Pear"] {
print(frucht)
}0..<3 yields 0, 1, 2 (0...3 would include the 3). The second loop runs directly over the array.
guard for early exits
Control flow#guard#optional#validation
Use case: Validating input and then continuing flat, instead of nesting deeply.
func alterInMonaten(_ text: String?) -> Int? {
guard let text, let jahre = Int(text), jahre >= 0 else {
return nil
}
return jahre * 12
}
print(alterInMonaten("30") ?? -1) // 360
print(alterInMonaten("-5") ?? -1) // -1
print(alterInMonaten(nil) ?? -1) // -1Multiple conditions are separated by commas. The else block must leave the function; afterwards text and jahre can be used safely.