Swift Numbers
A number is a value a program can combine with other numbers in maths.
Whole number maths
The four results are 10, 4, 21 and 3 in order. The last sum 7 / 2 gives 3 because the leftover part is dropped.
print(7 + 3)
print(7 - 3)
print(7 * 3)
print(7 / 2)Remainders
The first remainder is 1, from 7 divided by 3. The second remainder is -1, and its sign matches the first number in its sum.
print(7 % 3)
print(-7 % 3)Brackets change the result
The two lines print 14 and 20. The same numbers and operators give different results because the brackets move the addition first.
print(2 + 3 * 4)
print((2 + 3) * 4)Updating a stored number
The stored total changes at each step. Its printed values are 15, then 12, then 24.
var total = 10
total += 5
print(total)
total -= 3
print(total)
total *= 2
print(total)Decimal numbers
The first result prints as 3.5 with its decimal part kept. Doubles store most decimals approximately, so the second result prints as a long decimal instead of plain 0.3.
print(7.0 / 2)
print(0.1 + 0.2)Example
var score = 6
score *= 3
score += 2
print(score)
print(score % 5)Key points
- Programs do maths by joining number values with operators.
- The % operator gives what is left after a whole number division.
- A literal with a decimal point is a Double value.
- Multiplication happens before addition unless brackets group a part of the sum.
- Compound assignment updates a stored value with an operator such as +=, -= or *=.
In this example, score starts at 6. The *= line multiplies score by 3 and stores 18. The += line adds 2 and stores 20. The first print shows 20. The last print shows 0, the remainder when 20 is divided by 5.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Swift Compiler
Exercise
What does the whole number sum 7 / 2 print?