Numbers
Prerequisites: Data types and type inference
Swift's main number types are Int (whole numbers) and Double
(decimals). Int is 64 bits on modern devices, holding values up to
about 9.2 quintillion.
Example
print(7 + 2)
print(7 - 2)
print(7 * 2)
print(7 / 2)
print(7 % 2)
print(7.0 / 2)
print(10.0 / 3)
print(1_000_000 + 1)
Expected output
9
5
14
3
1
3.5
3.3333333333333335
1000001
Line by line:
7 / 2is3. Dividing twoInts gives anInt, dropping the remainder (integer division).%gives the remainder:7 % 2is1— handy for checking whether a number is even.- Dividing
Doubles gives aDouble. - Doubles are approximate:
10.0 / 3shows the tiny rounding error built into how computers store decimals. - Underscores in number literals are just for readability.
Mixing Int and Double
Swift won't mix an Int variable with a Double automatically.
Convert one side explicitly:
let items = 7
let people = 2
let share = Double(items) / Double(people)
print(share)
3.5
Useful number features
print(abs(-5))
print(max(3, 9))
print(min(3, 9))
print(10.isMultiple(of: 5))
print((3.7).rounded())
print(Int(3.99))
print(Int.random(in: 1...6) <= 6)
5
9
3
true
4.0
3
true
Int(3.99) truncates (cuts off the decimals) rather than rounding.
Int.random(in: 1...6) picks a random number from 1 to 6 — perfect for
dice.
Swift has no ** operator for powers; use pow(2.0, 10.0) after
import Foundation.
Common mistakes
- Integer overflow. Going past
Int.maxdoesn't wrap around silently — Swift stops the program with an overflow error. That's a safety feature. - Using
Doublefor money.0.1 + 0.2is0.30000000000000004. Store whole cents asInt, or use Foundation'sDecimaltype.
Practice
A pizza has 8 slices shared by 3 people. Print how many whole slices each person gets, how many are left over, and the exact share as a decimal.
Show solution
let slices = 8
let people = 3
print(slices / people)
print(slices % people)
print(Double(slices) / Double(people))
2
2
2.6666666666666665