Basic Swift, part 2 - Operators

Swift operators

Unary Minus Operator

Reverts the value to a negative value

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

Compound Assignment Operators

30
31
32
33
34
35
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

30
31
32
33
34
35
36
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

30
31
32
33
34
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

30
31
32
33
// loop through range of numbers from 0 to 4 (included)
for number in 0...4 {
  print(number)
}
30
31
32
33
// loop through range of numbers from 0 to 4 (excluded)
for number in 0...<4 {
  print(number)
}

Logical Operators

Not Operator (!)
30
31
32
33
let canAccess = false
if !canAccess { // ! inverts the variable
  print("Can access")
}
And Operator (&&)

Both values must be true

30
31
32
if 2 == 2 && 5 == 5 {
  return "Both are equal"
}
Or Operator (||)

One of the values must be true

30
31
32
if 5 == 2 || 5 == 5 {
  return "One of them is equal"
}
comments powered by Disqus