Skip to content

Basic Operators and Functions

In this chapter, you’ll get started with programming by performing basic calculations. You’ll use operators to build expressions, and Swift will evaluate those expressions for you. You’ll also learn about common functions needed for more complex calculations.

Operators

In Swift, the following symbols represent the four basic algebraic operations:

  • Addition: +
  • Subtraction: -
  • Multiplication: *
  • Division: /

These symbols are operators. You use them to build expressions:

swift
1 + 1
1.5 - 2.1
2 * -3
9.0 / 4.5

To display the value of an expression in your terminal, you use the print function:

swift
print(1 + 1)
print(1.5 - 2.1)
print(2 * -3)
print(9.0 / 4.5)

The remainder of this chapter will focus on the expressions themselves and leave out the print function. Remember to add it yourself when you want to see the value of an expression in your terminal.

Literals

The numbers you write in your code are known as literals. They express a numeric value, and you can combine them with operators to create a larger expression.

Swift differentiates between two types of number literals:

  • A literal that doesn’t contain a decimal point is a whole number or integer literal.
  • A literal that contains a decimal point is a floating-point literal.

This distinction between integers and floating-point numbers is important because you cannot freely mix both types of numbers in the same expression.

Formatting

You can use underscores to format large literals:

swift
1_000_000_000

These underscores don’t affect the value of the number; they only improve its readability.

Scientific notation

You can write floating-point literals using scientific notation. This notation consists of a significand, followed by the letter e and an exponent:

swift
12.1e12
1e-10

These numbers equal 12100000000000 and 0.0000000001, respectively.

Operands

The values on either side of an operator are its operands. Operators can restrict the types of operands they accept. For example, the algebraic operators require two operands of the same type and return a result that matches this type.

Compare the following expressions:

swift
9.0 / 4.0
9 / 4

In the first expression, both operands are floating-point numbers. Therefore, the operator performs a floating-point division and returns 2.25, as you would expect.

However, in the second expression, the result of the division is an integer because both operands are integers. In this case, the operator discards the fractional part and returns 2.

Note

It’s a common beginner’s mistake to divide two integers and expect a floating-point result.

When you mix integer and floating-point literals in the same expression, the result is a floating-point number. The following expressions are equivalent:

swift
1 - 2.1
1.0 - 2.1

Arity

Operators are often categorized based on the number of operands they accept; this is known as their arity. The operators you’ve seen so far all require two operands and are therefore called binary operators. However, some operators have only a single operand; these are unary operators.

In Advanced Control Flow, you’ll learn that Swift even has a ternary operator that takes three operands.

Remainder operator

Swift provides a helpful operator (%) that returns the remainder, after dividing the first operand by the second. For example:

swift
9 % 4

The result of this expression is 1, because 9 divided by 4 is 2, with a remainder of 1.

This operator works only on integers. For floating-point numbers, you can use one of the functions shown later in this chapter.

Precedence and associativity

Expressions can contain multiple operators. When that’s the case, the precedence of the operators involved determines the order in which they are applied. For the operators you’ve seen so far, the precedence is that multiplication, division, and remainder are performed before addition and subtraction. For this reason, the value of the following expression is 7, not 9:

swift
1 + 2 * 3

When operators with the same precedence are combined in an expression, their associativity determines the order in which they are applied.

In the following expression, / and * have the same precedence:

swift
2 - 12 / 3 * 4

Because these operators are left-associative — meaning they are applied from left to right — the division is performed before the multiplication, and the value of the expression is -14.

If you want to perform the multiplication first, add parentheses around the expression 3 * 4:

swift
2 - 12 / (3 * 4)

Expressions between parentheses are evaluated first, so this changes the value of the expression to 1.

Don’t expect your reader — or even yourself — to know the precedence and associativity of every operator. Add parentheses when they make your code easier to understand:

swift
2 - (12 / 3) * 4

Syntax

A programming language has rules that determine if the text you write is valid code. These rules are known as the syntax of the language.

One such rule is that binary operators must have whitespace on both sides or on neither side:

swift
1 - 2
1-2

Swift ignores additional whitespace, so these expressions are equivalent. However, the next two expressions are invalid because they have whitespace on only one side of the operator:

swift
1 -2
1- 2

Even though the syntax doesn’t require it, you should always add spaces around binary operators to improve the readability of your code.

Comments

Comments are notes from the programmer that are ignored by the compiler. It’s good practice to clarify your code with comments — just don’t overdo it.

Double slashes (//) create single-line comments. Everything after the slashes — up to the end of the line — is ignored:

swift
2 - 12 / 3 * 4 // We should clarify this with parentheses!

For longer comments, surround the comment with /* and */. This type of comment can span multiple lines, as the following example shows:

swift
/*
 Note to self:
 Always add spaces around binary operators!
 */

Functions

You can accomplish a lot with operators, but sooner or later, you’ll need the help of common functions like square root, logarithm, sine, and cosine.

These functions are provided by either the Swift Standard Library or the Foundation library. A library is a collection of code, ready for you to reuse, so you don’t have the reinvent the wheel every time you write a program. The Standard Library is available in every Swift program. However, to access Foundation, your code needs to import it first:

swift
import Foundation

Here are some of the functions you can access by importing Foundation:

  • Square root: sqrt
  • Power or exponentiation: pow
  • Natural logarithm: log
  • Base 10 logarithm: log10
  • Base 2 logarithm: log2
  • Sine: sin
  • Cosine: cos
  • Tangent: tan

You use these functions as follows:

swift
import Foundation

sqrt(16)
pow(4.0, 2.0)
log(1.0)
log10(1_000_000.0)
log2(1024.0)
sin(1.0)
cos(-1.0)
tan(2.0 * .pi)

Note

Some of these functions accept only floating-point numbers and not integer literals. Also, the functions only calculate a value — they don’t print it — so use print if you want to see the result.

The previous example used the number π. This number is available from the Standard Library as Double.pi — meaning π in double-precision floating-point — but as you can see, you can shorten this to .pi when you use it in an expression with other floating-point numbers.

As the Standard Library grows and matures, more and more functionality is added to it. The code below shows some of the functions already provided by the Standard Library. You don’t need to import Foundation to use these:

swift
abs(-12)
-12.signum()
min(3, 1, 4)
max(3, 1, 4)
12.isMultiple(of: 3)
16.0.squareRoot()
15.5.remainder(dividingBy: 6)
15.5.truncatingRemainder(dividingBy: 6)
16.6.rounded()
16.6.rounded(.down)

Note

This code uses features that weren’t covered yet, so it’s not explained in depth. It’s only meant to encourage you to explore and experiment.

Up next

In the next chapter, you’ll learn how you can store values in the computer’s memory. You’ll also learn about types and how they affect your code.