trailhead

Learn About Operators

Learning Objectives

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

  • Execute basic Swift mathematic operations.
  • Add two numbers of different types together.
  • Find the remainder of a division operation.

Operators are the symbols that make your code work. You use them to do things like check, change, or combine values. Swift has many types of operators, including ones to perform mathematical operations, logical operations, and complex assignments.

In this unit, you'll learn about some of the operators in the Swift language, including basic math operators for addition (+), subtraction (), multiplication (*), and division (/). 

Assigning a Value

Use the = operator to assign a value. The name on the left is assigned the value on the right.

This code declares that Luke is your favorite person:

let favoritePerson = "Luke"

The = operator is also used to modify or reassign a value.

The following code declares a shoeSize variable and assigns 8 as its value. The value is then modified to 9:

var shoeSize = 8
shoeSize = 9 // Reassigns shoeSize to 9

Basic Arithmetic

You can use the +, -, *, and / operators to perform basic math functionality:

var opponentScore = 3 * 8 // opponentScore has a value of 24
var myScore = 100 / 4 // myScore has a value of 25

You can use operators to perform arithmetic using the values of other variables:

var totalScore = opponentScore + myScore // totalScore has a value of 49

An operator can even reference the current variable, updating it to a new value:

myScore = myScore + 3 // Updates myScore to the current value plus 3

For decimal-point precision, you can do the same operations on Double values:

let totalDistance = 3.9
var distanceTravelled = 1.2
var remainingDistance = totalDistance - distanceTravelled // remainingDistance has a value of 2.7

When you use the division operator (/) on Int values, the result will be an Int value rounded down to the nearest whole number, because the Int type only supports whole numbers:

let x = 51
let y = 4
let z = x / y // z has a value of 12

If you explicitly declare constants or variables as Double values, the results will include decimal values.

let x: Double = 51
let y: Double = 4
let z = x / y // z has a value of 12.75

Make sure to use Double values whenever your code requires decimal-point accuracy.

Compound Assignment

An earlier code snippet updated a variable by adding a number to itself:

var myScore = 10
myScore = myScore + 3 // Updates myScore to the current value plus 3

But there's a better way to modify a value that's already been assigned. You can use a compound assignment operator, which adds the = operator after an arithmetic operator:

myScore += 3 // Adds 3 to myScore
myScore -= 5 // Subtracts 5 from myScore
myScore *= 2 // Multiples myScore by 2
myScore /= 2 // Divides myScore by 2

Compound assignment operators help you write cleaner, more concise code.

Order of Operations

Mathematic operations always follow a specific order. Multiplication and division have priority over addition and subtraction, and parentheses have priority over all four.

Consider the following variables:

var x = 2
var y = 3
var z = 5

Then consider the following calculations:

x + y * z // Equals 17
(x + y) * z // Equals 25

In the first line above, multiplication takes precedence over addition. In the second line, the parentheses get to do their work first.

Numeric Type Conversion

As you've learned, you can't mix and match number types when performing mathematical operations.

For example, the following will produce a compiler error, because x is an Int value and y is a Double value:

let x = 3
let y = 0.1415927
let pi = x + y

To enable the code to finish, you can create a new Double value from x by prefixing the type you want to convert it to:

let x = 3
let y = 0.1415927
let pi = Double(x) + y

In the revised code, Double(x) creates a new Double value from the Int value x, enabling the compiler to add it to y and assign the result to pi.

Complete the Lab

Ready to get hands-on experience with Swift? Practice what you learned with the exercises in Lab - Operators.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

let myNumber = (2 + 3) * (7 + 2)

For Quiz Question 2

var myNumber = 6
myNumber /= 3

Resources

retargeting