Integers
In this page:
Declaring Integers
The Int type represents whole numbers and is the default choice for integer values in Swift, automatically inferred from whole-number literals.
Example: Declaring Integers
let apples = 5
let oranges = 3
print("Total fruit: \(apples + oranges)")
Login to try C/C++/Java/PHP code in the editor
Integer Arithmetic
Swift supports the standard arithmetic operators on integers: addition, subtraction, multiplication, integer division, and the remainder operator.
Note: Integer division truncates any fractional part -- 17 / 5 is 3, not 3.4.
Example: Integer Arithmetic
let a = 17
let b = 5
print("\(a) / \(b) = \(a / b), remainder \(a % b)")
Login to try C/C++/Java/PHP code in the editor
Sized Integer Types
Beyond Int, Swift offers explicitly sized types like Int8, Int16, Int32, and Int64 for when you need to control exactly how much memory a value uses, such as when interfacing with specific binary formats.
Note: Underscores in numeric literals like 9_000_000_000 are ignored by the compiler and just help readability.
Example: Sized Integer Types
let small: Int8 = 100
let big: Int64 = 9_000_000_000
print("Int8: \(small), Int64: \(big)")
Login to try C/C++/Java/PHP code in the editor
- Assuming
Intis always 32-bit; on modern platformsIntis 64-bit, matching the native word size. - Overflowing a fixed-size integer type like
Int8and being surprised by a runtime crash instead of silent wraparound. - Mixing
IntandUInt(orIntandDouble) in an expression directly instead of explicitly converting first.
Intis the default integer type and matches the platform's native word size (64-bit on modern systems).- Swift also has sized variants like
Int8,Int16,Int32,Int64, and unsigned versions likeUInt. - Arithmetic operators (+, -, *, /, %) work as expected on integers.
- Integer overflow is checked and traps at runtime rather than silently wrapping, unless you use overflow-safe operators like
&+.
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: