Many times in our life, not only we choose to do something if a condition is met, but also choose to do something different if that condition is not met. For example:
If I'm tired:
I take a nap
Otherwise:
I start coding
If-else Statements:
When a condition for an if statement is true, the block of code following it is executed. What about when that condition is false? Normally nothing would happen.
With an else statement, we can have an alternate block of code to be executed. For example:
var amTired = false
if amTired {
print("I take a nap")
} else {
print("I start coding")
}
The code above prints "I start coding" since the expression inside the if evaluates to false and so Swift will enter the else statement and execute the code inside it.
An else statement cannot exist without a corresponding if statement. This combination is refered to as an if-else statement.
Assignment
Follow the Coding Tutorial and let's practice with if-else statements!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.