Swift operators

Unary Minus Operator

Reverts the value to a negative value

unary.swift
1
2
let two = 2
let minusTwo = -two // (-) unary operator, returns -2

Compound Assignment Operators

assignment.swift
1
2
3
4
5
6
var foo = 1

foo += 2          // same as foo = foo + 2, result 3
foo -= 1          // same as foo = foo - 1, result 2
foo *= 3          // same as foo = foo * 3, result 6
foo /= 2          // same as foo = foo / 2, result 3

Comparison Operators

comparison.swift
1
2
3
4
5
6
7
var bar = 3
foo == bar        // compares if foo is equal to bar
foo != bar        // compares if foo is diferent from bar
foo > bar         // compare if foo is bigger than bar
foo < bar         // compare if foo is smaller than bar
foo >= bar        // compare if foo is bigger or equal than bar
foo <= bar        // compare if foo is smaller or equal than bar

Nil Coalescing Operator

Nil coalescing operator allows the falback to a second option

coalescing.swift
1
2
3
4
5
var food = "banana"

var drink: String?           // (?) maskes variable optional, value is in question, maybe exists maybe it does not

var stomach = food ?? drink // (??) coalescing operator if no food, then drink

Range Operator

Goes through a sequence of numbers

range.swift
1
2
3
4
// loop through range of numbers from 0 to 4 (included)
for number in 0...4 {
  print(number)
}
range2.swift
1
2
3
4
// loop through range of numbers from 0 to 4 (excluded)
for number in 0...<4 {
  print(number)
}

Logical Operators

Not Operator (!)
notOperator.swift
1
2
3
4
let canAccess = false
if !canAccess { // ! inverts the variable
  print("Can access")
}
And Operator (&&)

Both values must be true

and.swift
1
2
3
if 2 == 2 && 5 == 5 {
  return "Both are equal"
}
Or Operator (||)

One of the values must be true

or.swift
1
2
3
if 5 == 2 || 5 == 5 {
  return "One of them is equal"
}