Order of operations
Of course, it’s likely that when you calculate a value, you’ll want to use multiple operators. Here’s an example of how to do this in Swift:
((8000 / (5 * 10)) - 32) >> (29 % 5)
Notice the use of parentheses, which in Swift serve two purposes: to make it clear to anyone reading the code — including yourself — what you meant, and to disambiguate. For example, consider the following:
350 / 5 + 2
Does this equal 72 (350 divided by 5, plus 2) or 50 (350 divided by 7)? Those of you who paid attention in school will be screaming “72!” And you would be right!
Swift uses the same reasoning and achieves this through what’s known as operator precedence. The division operator (/) has a higher precedence than the addition operator (+), so in this example, the code executes the division operation first.
If you wanted Swift to do the addition first — that is, to return 50 — then you could use parentheses like so:
350 / (5 + 2)
The precedence rules follow the same that you learned in math at school. Multiply and divide have the same precedence, higher than add and subtract which also have the same precedence.