In programming, increasing the value of a variable by 1 is so common that many languages have an operator designed to do that: the increment operator (++).
Swift has no ++ operator (it was removed in Swift 3). Instead, you use the augmented assignment += with 1:
var number = 10
number += 1 // short for number = number + 1
print(number) // Output: 11
Other languages also have an operator for decreasing the value of a variable by 1, the decrement operator (--). Swift has no -- either, so you use -= with 1:
var number = 10
number -= 1 // short for number = number - 1
print(number) // Output: 9
Postfix:
In languages that have them, the operators can be used in their postfix form, with the operator after the operand, such as number++.
If used postfix, the increment operator increments and returns the value before incrementing. Swift has no such operator, but you can get the same result by reading the value first and then incrementing:
var number = 10
var oldNumber = number
number += 1
print(oldNumber) // Output: 10
print(number) // Output: 11
This code first assigns the value of number (which is 10) to oldNumber and then increments number (making it 11). That is what a postfix increment does in other languages.
Prefix:
There is also the prefix form, with the operator before the operand (for example, ++number in other languages).
When used prefix, the increment operator increments and returns the value after incrementing. In Swift you write it as two statements:
var number = 10
number += 1
var newNumber = number
print(newNumber) // Output: 11
print(number) // Output: 11
This code first increments number (making it 11) and then assigns the new value of number to newNumber (making it 11).
Here's the same idea with a decrement:
var number = 10
number -= 1
var newNumber = number
print(newNumber) // Output: 9
print(number) // Output: 9
Assignment
Follow the Coding Tutorial and let's practice with these operators!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
