Start tracking your progress
Trailhead Home
Trailhead Home

Learn About Control Flow

Learning Objectives

After completing this unit, you’ll be able to:

  • Use if and else statements to control what code is executed.
  • Use the logical operators to check if something is true or false.
  • Use a switch statement to control what code is executed.
  • Use the ternary operator to conditionally assign different values to a constant or variable.

In the Get Started with Swift unit, you learned that a Swift program is written in a .swift file that's executed from top to bottom. You also saw this as you worked in playground files. But large applications aren't so simple. They don't fit into one file, and they usually don't run every line of code from top to bottom.

You will write code that makes decisions about what lines of code should be executed depending on results of previously executed code. This is called control flow.

In this lesson, you'll learn how to use logical operators to check conditions and to use control flow statements (if, if-else, and switch) to choose what code will be executed as a result.

Think of an application you use that requires you to log in. If you launch the application and you're already logged in, the app displays your data. If you're not logged in, the app asks for your login credentials. If you enter a correct username and password, you're logged in and the app displays your data. If you enter incorrect credentials, you're asked to enter the correct information.

This example describes one common interaction that requires multiple checks and runs code based on the results.

These checks are called conditional statements, and they're part of a broader concept called control flow. As a developer, you have control flow tools that check for certain conditions and execute different blocks of code based on those conditions.

Based on the outcome of a set of conditions, you can use a variety of statements to control what code is executed. These conditional statements are all examples of control flow.

Logical Operators

Each if statement uses a logical operator to decide if something is true or false. The result determines whether to run the block of code or to skip it.

Start by taking a look through this list of the most common logical operators:

Operator
Description
==
Two items must be equal
!=
The values must not be equal to each other
>
Value on the left must be greater than the value on the right
>=
Value on the left must be greater than or equal to the value on the right
<
Value on the left must be less than the value on the right
<=
Value on the left must be less than or equal to the value on the right
&&
AND—The conditional statement on the left and right must be true
||
OR—The conditional statement on the left or right must be true
!
NOT—Returns the opposite of the conditional statement immediately following the operator

You can mix and match logical operators to create what's called a Boolean value, or Bool. Boolean values are either true or false and can be combined with an if statement to determine if code should be run or skipped.

If Statements

The most straightforward conditional statement is the if statement. An if statement basically says, "If this condition is true, then run this block of code." If the condition isn't true, the program will skip the block of code.

In most cases, you'll use an if statement to check simple conditions with only a few possible outcomes. Here's an example:

let temperature = 100
if temperature >= 100 {
 print("The water is boiling.")
}

This will print the following:

The water is boiling.

The temperature constant is equal to 100 and the if statement prints text if temperature is greater than or equal to 100. Because the if statement resolves to true, the block of code accompanying the if statement is executed.

If-Else Statements

You just learned that an if statement will run a block of code if the condition is true. But what if the condition isn't true? By adding an else to an if statement, you can specify a block of code to execute if the condition is not true:

let temperature = 100
if temperature >= 100 {
 print("The water is boiling.")
} else {
 print("The water is not boiling.")
}

You can take this idea even further. By using else if, you can declare more blocks of code to run based on any number of conditions. The following code checks for the position of an athlete in a race and responds accordingly:

var finishPosition = 2
if finishPosition == 1 {
 print("Congratulations, you won the gold medal!")
} else if finishPosition == 2 {
 print("You came in second place, you won a silver medal!")
} else {
 print("You did not win a gold or silver medal.")
}

You can use many else if statements to account for any number of potential cases.

Boolean Values

You can assign the results of a logical operator to a Bool constant or variable in order to check or access the value later. Bool values can only be true or false.

In the following code, the Bool statement determines that number doesn't qualify as isSmallNumber:

let number = 1000
let isSmallNumber = number < 10 // number is not less than 10, so isSmallNumber is assigned a `false` value

And here, the Bool statement determines that currentSpeed does qualify as isSpeeding:

let speedLimit = 65
let currentSpeed = 72
let isSpeeding = currentSpeed > speedLimit // currentSpeed is greater than the speedLimit, so isSpeeding is assigned a `true` value

It's also possible to invert a Bool value using the logical NOT operator, which is represented by !:

var isSnowing = false
if !isSnowing {
 print("It is not snowing.")
}

This will print the following:

It is not snowing.

In the same way, you can use the logical AND operator, represented by &&, to check if two or more conditions are true:

let temperature = 70
if temperature >= 65 &amp;&amp; temperature <= 75 {
 print("The temperature is just right.")
} else if temperature < 65 {
 print("It is too cold.")
} else {
 print("It is too hot.")
}

This will print the following:

The temperature is just right.

In the code above, the temperature meets both conditions: It's greater than or equal to 65 degrees and less than or equal to 75 degrees; it's just right.

You have yet another option: the logical OR operator, represented by ||, to check if either one of two conditions is true:

var isPluggedIn = false
var hasBatteryPower = true
if isPluggedIn || hasBatteryPower {
 print("You can use your laptop.")
} else {
 print("😱")
}

This will print the following:

You can use your laptop.

The example above prints You can use your laptop. Even though isPluggedIn is false, hasBatteryPower is true, and the || OR operator has determined that one of the options is true.

Switch Statement

You've seen if statements and if-else statements that allow you to run certain blocks of code depending on certain conditions. But nested if statements can become messy and hard to read after a small number of options. Swift has another tool for control flow called a switch statement, which is great for working with many potential conditions.

A basic switch statement takes a value with multiple options and allows you to run separate code based on each option, or case. You can also provide a default case to specify a block of code that will run in all the cases you haven't specifically defined.

Consider the code that prints a name for a vehicle based on its number of wheels:

let numberOfWheels = 2
switch numberOfWheels {
 case 1:
  print("Unicycle")
 case 2:
  print("Bicycle")
 case 3:
  print("Tricycle")
 case 4:
  print("Quadcycle")
 default:
  print("That's a lot of wheels!")
}

Given a constant numberOfWheels, the code provides a separate action if the value is 1, 2, 3, or 4. It also provides an action if numberOfWheels is anything else.

This code could be written as a nested if-else statement, but it would quickly become tricky to parse.

Any given case statement can also evaluate multiple conditions at once. The following code, for example, checks whether a character is a vowel or not:

let character = "z"
switch character {
 case "a", "e", "i", "o", "u" :
  print("This character is a vowel.")
 default:
  print("This character is a consonant.")
}

When working with numbers, you can use interval matching to check for inclusion in a range. Take a look at the syntax in the following code snippet:

let distance = 25
switch distance {
 case 0...9:
  print("Your destination is close.")
 case 10...99:
  print("Your destination is a medium distance from here.")
 case 100...999:
  print("Your destination is far from here.")
 default:
  print("Are you sure you want to travel this far?")
}

The switch operator is the right tool for control flow when you want to run different code based on many different conditions.

Ternary Operator

An interesting (and very common) use case for an if statement is to set a variable or return a value. If a certain condition is true, you want to set a variable to one value. If the condition is false, you want to set the variable to a different value.

Consider the following code. It checks if the value of one number is greater than the other and assigns the higher value to a largest variable:

var largest = 0
let a = 15
let b = 4
if a > b {
 largest = a
} else {
 largest = b
}

Because this situation is so common in programming, many languages include a special operator, called a ternary operator (?:), for writing more concise code.

The ternary operator has three parts:

  1. A question with a true or false answer.
  2. A value if the answer to the question is true.
  3. A value if the answer to the question is false.

Here's an example:

var largest = 0
let a = 15
let b = 4
largest = a > b ? a : b

Take a close look at the last line of code. You can read it as: "If a > b, assign a to the largest constant; otherwise, assign b." In this case, a is greater than b, so it's assigned to largest.

Keep in mind that you're never required to use the ternary operator in Swift. But the ternary operator is very useful shorthand for assigning a value based on a condition, rather than resorting to a more complex if-else statement.

Complete the Lab

Ready to get hands-on experience with Swift? Practice what you learned with the exercises in Lab - Control Flow.playground.

Before Taking the Quiz

We're taking a unique approach to testing your knowledge about Operators. Below are some Swift code samples. In the quiz, we ask you questions that will require you to assess the code and verify you understand how it works. Good luck!

For Quiz Question 1

var time = 6
    if time < 12 {
  print("Good morning")
} else if time < 18 {
  print("Good afternoon")
} else {
  print("Good evening")
}

For Quiz Question 2

var grade: Character = "F"
let score = 78
switch score {
case 90...100:
  grade = "A"
case 80...89:
  grade = "B"
case 70...79:
  grade = "C"
case 61...69:
  grade = "D"
default:
  grade = "F"
}

Resources

retargeting