Making Decisions
7 min · Swift
Run different code depending on whether something is true.
Enemy 1 of 5
Nearly every useful program needs to make decisions: only offer free shipping if the order total is high enough, only show a message if a form field is empty, and so on. Swift builds that decision-making with if. An if checks a condition — an expression that evaluates to true or false — and runs the code inside its { } block only when that condition holds.
Pairing if with else provides a fallback path for when the condition is false: exactly one of the two blocks runs, never both, never neither.
Notice Swift's if doesn't require parentheses around the condition — you write if temperature > 20 { ... }, not if (temperature > 20) { ... } — which matches Rust but differs from Kotlin, Java, and C, all of which require the parentheses. The curly braces, on the other hand, are always mandatory in Swift, even for a single-line block, which rules out a classic C-family bug where an unindented line silently falls outside the block it was meant to belong to.
Loading editor...