Operators
We will take a quick tour of the most common operators in Swift, leaving such esoteric topics as custom operators for Chapter 5, Advanced Swift.
Mathematical operators
The five basic math operators will need no explanation here:
- + * / %
They are so-called infix operators, meaning that they are placed between their two operands:
let x = (a * a) + (b * b)
The usual rules of precedence apply.
Augmented assignment
As in many other C-derived languages, we can replace:
x = x + 1
With:
x += 1
There are versions of this for the other mathematical operators:
-= *= /= %=
Readers should already be familiar with all these operators.
Note
There is no ++
or --
operator in Swift 3. Older versions of the language did, in fact, retain these from the C family of languages, so don't be too surprised if you come across it in older posts on the Web. If you do need to do an i++
or i--
(although for
loops make these operators largely unnecessary), use i += 1
or i -= 1
.
Comparison operators
Swift's comparison...