Simple operations
All operations in Swift use a symbol known as the operator to denote the type of operation they perform.
Consider the four arithmetic operations you learned in your early school days: addition, subtraction, multiplication and division. For these simple operations, Swift uses the following operators:
- Add: +
- Subtract: -
- Multiply: *
- Divide: /
These operators are used like so:
2 + 6
10 - 2
2 * 4
24 / 3
Each of these lines is what is known as an expression. An expression has a value. In these cases, all four expressions have the same value: 8. You write the code to perform these arithmetic operations much as you would write it if you were using pen and paper.
In your playground, you can see the values of these expressions in the right-hand bar, known as the results sidebar, like so:
If you want, you can remove the white space surrounding the operator:
2+6
Removing the whitespace is an all or nothing, you can't mix styles. For example:
2+6 // OK
2 + 6 // OK
2 +6 // ERROR 2+ 6 // ERROR
It’s often easier to read expressions if you have white space on either side of the operator.