All lessons

Making Decisions

7 min · Swift

Run different code depending on whether something is true.

Swift · Making Decisions0/5 cleared

Enemy 1 of 5

This code checks if temperature is above 20. It is not, so the else block runs instead. Press Run to see Cold.

Why this works

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.

You
Memory-Leak Rat
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.