Math in Swift

Arithemetic Operations

Tested on: Xcode 12.2, Swift 5.3

Arithmetic operations allow you to perform common mathematical operations in Swift like Addition (+), Subtraction (-), Multiplication (*), Division (/) and more. These operations allow you to convert one or more pieces of data into another piece of data such as 1 + 2 = 3.

In most applications, simple arithmetic operations are used to calculate the number of likes in a post or the number of followers you have. Numbers are everywhere in an app. Therefore, it is important to understand them. In this reference, we will cover :

  1. Simple Arithmetic Operations (Add, Subtract, Multiply, Divide, Modulus)
  2. Compound Assignment Operators (Increment and Decrement)





1. Simple Arithmetic Operations

Some of you might already know most of these operations as you learnt them during your school days. Operators use a symbol to represent them. The most basic operators are:

Addition +

Swift Code :

12 + 15

Output :

27

Subtraction -

Swift Code :

12 - 20

Output :

-8

Mutiplication *

Swift Code :

20 * 2

Output :

30

Division /

In division, it is important to take note of thedata type. The example shown below, 16.0 divide 3.0 as you know it will be equal to is 15.3333. However, if both values are integer such as 16 / 3. Swift will return an integer. Therefore, the resulted outcome is 15and not 15.3333. Note: Swift round the value down.

Swift Code :

16.0 / 3.0

Output :

5.333333


Swift Code :

16 / 3

Output :

5

Modulus (Remainder) %

The four operators above are easy to understand as you used them frequently in your life. Modulus or Remainder operator in Swift, return the remainder of the result when a division is done. For example, 16 % 3 = 5.33333.5.33333 - 5 = 0.33333.0.33333 * 3 = 1.

To simpify it, 3 goes into 16 four times with a remainder of 1.

For example,

Swift Code :

16 % 3

Output :

1

Note: Whitespace

In Swift, the whitespace of the left and right of the operator must be the same. Meaning if you put, space before the operator after also need whitespace and vice versa. If not, it will result in an error.

Swift Code :

16 /3

Output :

error: consecutive statements on a line must be separated by ';'

You are only allowed to do one of the following stated below: (Spaces or no Spaces)

Swift Code :

16 / 3
16/3



2. Compound Assignment Operators

Compound Assignment Operators combine assignment operator = with other operators such as arithmetic operators. Take a look at the following example below:

level += 1 is the same aslevel = level + 1. Meaning addition is done first by doing 1 + 1 and the resulted outcome 2 is then assigned back to level.

Swift Code :

var level = 1
level += 1