If-Else Statements

In Swift, you can use an if-else statement to let your program make decisions.

For example, let’s check if a person can drive based on their age:

let age = 15

if age < 18 {
    print("You cannot drive")
} else {
    print("You can drive")
}

This results in the following output in the console:

You cannot drive

If-else statements are everywhere.

They are the basic building blocks of programming. With if-else statements, you can start implementing actual logic in your code.

So far in this series, you have only declared variables and constants, and done some basic maths. But this is where the real programming part starts.

In this chapter, you are going to learn how to use if-else statements. All the theory is backed up with great and illustrative examples.

Let’s start with the if-statements.

This chapter is part of a completely free Swift for Beginners guide. Make sure you have completed all the chapters from the start before reading this one.

Disclaimer: To learn Swift, you have to repeat everything you see in this guide and in the following guides. If you only read the guides, you are not going to learn anything!

If Statements in Swift

In Swift, you can use if-else statements to check if a condition holds.

The most basic way to check if a condition holds is by using an if-statement.

The if statement follows this syntax:

if condition {
    // code here
}

The if statement:

  • Starts with the if keyword.
  • After the if keyword, there is a condition that is checked.
  • The condition is followed by a block of code marked with curly brackets {}.

If the condition is true, the block of code is executed.

If the condition is not true, the following block of code is skipped. The program continues running code normally after the block.

The best way to learn is by examples, so let’s see one. Please, repeat this example in your own playground, and feel free to modify the condition/actions.

For example, let’s print “Welcome” into the console if a person is older than 25:

let age = 30

if age > 25 {
    print("Welcome!")
}

Output:

Welcome!

Let’s take a deeper look at the condition in the if statements.

What Exactly is the Condition in an If Statement?

Earlier in this series, you learned what is a boolean value (Bool) in Swift.

To recap, a boolean value means something is either true or false.

In Swift, the Bool data type represents boolean values.

In the previous chapter, you learned how to use an if statement to check if a condition holds.

A more formal way to put it is you can use an if statement to check if a boolean value evaluates true.

Take another look at the general syntax of the if statement.

if condition {
    // code here
}

Here the condition is any boolean value that is either true or false.

In other words, the condition can be anything as long as it produces true or false.

Here are some examples.

Example 1: Comparisons

You can use an if-statement to make comparisons.

For instance, you can compare numbers:

let n = 10
let m = 10

if n == m {
    print("n and m are equal")
}

Output:

n and m are equal

Notice that you do not need to store the numbers into separate constants or variables. You can make comparisons directly in the if statement.

For example, let’s check if the result of a multiplication is greater than another:

if 3 * 8 < 4 * 7 {
    print("3 x 8 is less than 4 x 7")
}

Output:

3 x 8 is less than 4 x 7

Example 2: Check Converted Booleans

In boolean context 0 is false, and everything else is true.

Thus, you can use an if-statement to check if a number would be true or false.

For example:

if Bool(1) {
    print("1 is true")
}

if Bool(231) {
    print("231 is true too")
}

if Bool(0) {
    print("This will not be executed")
}

Output:

1 is true
231 is true

Example 3: Chain Multiple Conditions

In Swift, you can chain multiple conditions together. This lets you avoid writing if statements inside an if statement.

For example:

var isSunny = true
var isHot = true
var isFreeTime = true

if isSunny && isHot && isFreeTime {
    print("Let's go to the beach")
}

Output:

Let's go to the beach

In this example, we only go to the beach if it is sunny and hot and if we have free time.

If you did not chain the conditions together, you would need to write if-statements inside other if-statements to make the code work:

var isSunny = true
var isHot = true
var isFreeTime = true

if isSunny {
    if isHot {
        if isFreeTime {
            print("Let's go to the beach")
        }
    }
}

Even though this piece of code works identical to the previous one, this looks way worse.

At this point, you have a basic understanding of how to check if a condition holds in Swift using if statements.

But how about when the condition does not hold?

This is where you can use the else statement.

If-Else Statements

In Swift, the if-else statement can be used to run code if a condition holds or if it doesn’t.

In the previous chapter, you solely used an if statement to check if a condition is true.

But more often than not, you want to also perform actions if the condition does not hold.

This is where you can use an if-else statement.

The basic syntax of the if-else statement looks like this:

if condition {
   // run code on true
} else {
   // run code on false
}

This code construct works such that:

  • If the condition is true, the code block followed by it gets executed.
  • If the condition is false, only the else block is executed.

Once again, this is best demonstrated with an example.

For instance, let’s check if a person can drive based on their age:

let age = 15

if age >= 18 {
    print("You can drive")
} else {
    print("You cannot drive")
}

Output:

You cannot drive

Let’s take a closer look at how this code gets executed.

  1. Swift specifies an integer constant called age and gives it a value of 15.
  2. Then Swift checks if the age is greater than or equal to 18. In this case, it is false.
  3. Because the condition is false, Swift jumps to the else block and runs the code in it.
  4. This prints “You cannot drive” into the console.

Keep in mind you do not have to write an else statement if you do not need one.

It is quite common for beginners to think that you always have to write an else statement.

But this is not the case.

Now you understand how to use if-else statements to run code based on a condition.

However, it is quite common to have multiple conditions instead of just two.

To check multiple conditions in an if-else statement, you can use an else-if statement.

Else-If Statements

In Swift, you can specify multiple condition checks in the same if-else statement using an else-if block.

Here is the syntax:

if condition1 {
    // actions1
} else if condition2 {
    // actions2
} else {
    // actions3
}

Here:

  • Swift checks the condition1. If it is true, only code block with actions1 is executed.
  • If the condition1 is false, Swift then checks condition2. If it is true, the actions2 are executed.
  • If neither condition above was true, the else block is executed with actions3.

Let’s see an example:

let age = 17

if age >= 18 {
    print("You can drive")
} else if age == 17 {
    print("Go to driving school")
} else {
    print("You cannot drive")
}

Output:

Go to driving school

As you can see, because the age is 17, the first condition is not true. But the second condition in the else-if block is true, so the code in it gets executed.

Using the else-if block is a practical way to check for multiple conditions.

Next, let’s see how you can chain these else-if statements together.

Chaining Else If Statements

If you have more than 3 conditions, you can chain together as many else-if statements as you want.

if condition1 {
    // actions1
} else if condition2 {
    // actions2
} else if condition3 {
    // actions3
} else if condition4 {
   // actions4
} 
  .
  .
  .
  else {
   // actionsn
}

Let’s also see a quick example of this.

let age = 13

if age >= 18 {
    print("You can drive")
} else if age == 17 {
    print("Go to driving school")
} else if age > 12 && age < 17 {
    print("Teens can't drive")
} else if age <= 12 {
    print("Kids can't drive")
} else {
    // age is less than 0
    print("Invalid age")
}

Output:

Teens can't drive

Cool! There is quite a bit of code already.

This completes our guide on if-statements in Swift.

Next Chapter: Switch Case Statement

Conclusion

Today you learned how to use if-else statements in Swift.

To recap, an if-else statement lets you introduce logic to your code. With if-else statements, the code can make decisions.

If-else statements are the basic building blocks of coding, so make sure you thoroughly understand how they work.

When using if-else statements, you can:

  • Only write an if statement to check if a condition is true.
  • Write an if-else statement to run code on true and run some other code on false.
  • Check multiple conditions with one or more else-if statements.

In the next chapter, you are going to learn an alternative to the if-else statement.

Next Chapter: Switch Case Statement