This tutorial belongs to the Swift series

We can use a wide set of operators to operate on values.

We can divide operators in many categories. The first is the number of targets: 1 for unary operators, 2 for binary operators or 3 for the one and only ternary operator.

Then we can divide operators based on the kind of operation they perform:

  • assignment operator
  • arithmetic operators
  • compound assignment operators
  • comparison operators
  • range operators
  • logical operators

plus some more advanced ones, including nil-coalescing, ternary conditional, overflow, bitwise and pointwise operators.

Note: Swift allows you to create your own operators and define how operators work on your types you define.

Assignment operator

The assignment operator is used to assign a value to a variable:

var age = 8

Or to assign a variable value to another variable:

var age = 8
var another = age

Arithmetic operators

Swift has a number of binary arithmetic operators: +, -, *, / (division), % (remainder):

1 + 1 //2
2 - 1 //1
2 * 2 //4
4 / 2 //2
4 % 3 //1
4 % 2 //0

- also works as a unary minus operator:

let hotTemperature = 20
let freezingTemperature = -20

+ is also used to concatenate String values:

"Roger" + " is a good dog"

Compound assignment operators

The compound assignment operators combine the assignment operator with arithmetic operators:

  • +=
  • -=
  • *=
  • /=
  • %=

Example:

var age = 8
age += 1

Comparison operators

Swift defines a few comparison operators:

  • ==
  • !=
  • >
  • <
  • >=
  • <=

You can use those operators to get a boolean value (true or false) depending on the result:

let a = 1
let b = 2

a == b //false
a != b //true
a > b // false
a <= b //true

Range operators

Range operators are used in loops. They allow us to define a range:

0...3 //4 times
0..<3 //3 times

0...count //"count" times
0..<count //"count-1" times

Here’s a sample usage:

let count = 3
for i in 0...count {
  //loop body
}

Logical operators

Swift gives us the following logical operators:

  • !, the unary operator NOT
  • &&, the binary operator AND
  • ||, the binary operator OR

Sample usage:

let condition1 = true
let condition2 = false

!condition1 //false

condition1 && condition2 //false
condition1 || condition2 //true

Those are mostly used in the if conditional expression evaluation:

if condition1 && condition2 {
  //if body
}