Swift's exhaustive switch and guard statements are used constantly and differ from C-style languages.
if conditions must be a real Bool — there is no truthiness, so if count { } doesn't compile. Parentheses around the condition are optional; braces are mandatory.
for item in collection iterates anything that is a Sequence. Ranges are written 0..<n (half-open) and 1...n (closed); stride(from:to:by:) gives other steps. while and repeat { } while loop on a condition.
switch must be exhaustive and does not fall through: the first matching case runs and the statement ends, so no break is needed. Cases can match several values (case "a", "e":), ranges (case 90...:), tuples, and bind values with let plus a where clause. Use default when you can't list every case.
guard condition else { return } states a requirement up front and exits early otherwise. The else branch must leave the scope (return, throw, break, continue). This keeps the happy path unindented.
Since Swift 5.9, if and switch can be used as expressions when each branch is a single expression: let label = if score > 50 { "pass" } else { "fail" }.
Use continue and break in loops, and labeled statements (outer: for ...) to break out of nested loops.
Example
func grade(_ score: Int) -> String {
guard score >= 0 else { return "invalid" }
switch score {
case 90...: return "A"
case 75..<90: return "B"
case let s where s % 2 == 0: return "even C"
default: return "C"
}
}
for s in [95, 80, 42, -1] {
print(grade(s)) // A, B, even C, invalid
}
let mood = if Bool.random() { "happy" } else { "calm" }
for i in stride(from: 10, to: 0, by: -3) {
print(i, terminator: " ") // 10 7 4 1
}Remember
switchis exhaustive and never falls throughguard ... elseexits early and keeps the happy path flat..<is half-open,...is closed
Watch out for
- Writing
fallthroughhabits from C — in Swift each case ends automatically.