Start learning free

LESSON 66 OF 349 · CONDITIONAL STATEMENTS

If Statements in Swift in Swift

Lesson

TL ; DR:

  • if statements allow us to build programs that can make decisions based on some conditions. Here is the syntax:

    var isRainy = true
    if isRainy {
        print("I bring an umbrella")
    }
    



Full lesson:

As humans, we often make decisions based on conditions. For example, we might go through these decision-making processes during a day:

If it's rainy:
  I bring an umbrella

If I'm hungry:
  I have breakfast

I I'm tired:
  I take a nap

We can also tell the computer to make decisions like these in our programs.


If Statements:

if statements allow us to build programs that can make decisions based on some conditions. Here is the syntax:

if conditions {
    // instructions
}

The keyword if tells Swift to execute the code inside the curly braces (where we have our Swift comment) only if the conditions defined in the parentheses are met.


Boolean conditions:

The conditions inside if statements are known as Boolean conditions and they may only be true or false.

If the boolean condition evaluates to true, the program executes the statements inside curly braces. If it evaluates to false, the statements will not execute.

If you check our example, you'll see that all the conditions there (it's rainy, I'm hungry and I'm tired) are Boolean conditions.

Let's turn those decisions into working code using if statements:

var isRainy = true
if isRainy {
    print("I bring an umbrella")
}

The code above prints "I bring an umbrella" since the condition in the parentheses evaluates to true

But this code:

var amHungry = false
if amHungry {
    print("I have breakfast")
}

prints nothing since amHungry evaluates to false.


Assignment
Follow the Coding Tutorial and let's practice with if statements!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    If Statements 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