What an if-else statement does
An if statement runs a block of code only when a condition is true. When the condition is false, the program skips the block and carries on, so nothing is reported. An else branch gives the program something to do in that second case. Exactly one of the two blocks runs, never both and never neither.
In everyday terms: if I'm tired, I take a nap; otherwise, I start coding. Swift writes it like this:
var amTired = false
if amTired {
print("I take a nap")
} else {
print("I start coding")
}
Because amTired is false, the program prints I start coding. Change the value to true and it prints I take a nap instead.
The syntax
A few rules apply to every Swift if:
- The condition has no parentheses. You can add them, as in
if (amTired) {, and the code still compiles, but idiomatic Swift leaves them out. - The braces are required. Even when the body is a single statement, Swift needs
{and}. A body without braces is a compile error. - The condition must be a
Bool. Swift does not treat numbers as true or false. Withlet count = 1, writingif count {fails withtype 'Int' cannot be used as a boolean; test for '!= 0' instead. Write the comparison you mean, such ascount != 0. elsehas no condition. It runs whenever theifcondition is false, so you never write a test after it.elsebelongs to anif. It can't appear on its own, only attached to the closing brace of theifblock before it.
The usual style puts else on the same line as the closing brace: } else {. Swift ignores line breaks here, so this also compiles with else on its own line, but the one-line form is what Swift code normally looks like.
The exercise
The starting code declares passed as a Bool set to false and prints Passed the test when it is true. With the value false, the program prints nothing at all. The task is to attach an else branch that prints Failed the test, so the program reports a result either way.
- Find the closing brace of the
ifblock, the}after the firstprint. - Write
elseafter it on the same line, followed by an opening brace:} else {. - Add the
printcall for"Failed the test"inside the new block. - Close the new block with its own
}.
The finished program:
var passed: Bool = false
if passed {
print("Passed the test")
} else {
print("Failed the test")
}
It prints Failed the test. Setting passed to true makes it print Passed the test instead.
Going further: more than two outcomes
When there are more than two cases, chain the tests with else if. Swift checks the conditions from top to bottom and runs the first block whose condition is true. The final else catches whatever is left.
let temperature = 15
if temperature < 10 {
print("cold")
} else if temperature < 20 {
print("mild")
} else {
print("warm")
}
This prints mild. The first test fails, the second passes, and the else is never reached.
For a simple choice between two values, Swift also has the ternary operator condition ? a : b. With passed equal to true, let label = passed ? "yes" : "no" gives "yes". Use the full if-else when a branch does more than produce a value.
Common mistakes
- Writing
=instead of==. Withvar x = 3, the lineif x = 5 {fails withuse of '=' in a boolean context, did you mean '=='?. A single=assigns;==compares. - Giving
elsea condition.else (x > 3) {is not valid. To test something else, useelse if. - Using a number as the condition. Compare it with a value instead of relying on it being zero or non-zero.
- Forgetting that the branches are exclusive. If the
ifblock runs, theelseblock is skipped entirely.
Key takeaways
ifruns a block when its condition is true;elseruns a block when it is false.- The condition is a
Boolwith no parentheses, and the braces are always required. - Use
else ifto chain several tests, and finish withelsefor the remaining case. - Write
} else {on one line, and use==, not=, to compare.
