Start learning free

LESSON 67 OF 349 · CONDITIONAL STATEMENTS

If-else Statements in Swift in Swift

Lesson

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.


STEP 1 OF 1
    Ctrl + Enter to check

    If Else in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free