Skip to content

Swift Operators

New Course Coming Soon:

Get Really Good at Git

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:

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:

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
}
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my Swift Handbook

Here is how can I help you: