← Back to Swift Course | Chapter 2: Variables & Types | Lesson 4 of 8

Integers

Integers are whole numbers, like 1, 2, or -7, with no fractions or decimal points.

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

markup
let apples = 5
let oranges = 3
print("Total fruit: \(apples + oranges)")

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

markup
let a = 17
let b = 5
print("\(a) / \(b) = \(a / b), remainder \(a % b)")

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

markup
let small: Int8 = 100
let big: Int64 = 9_000_000_000
print("Int8: \(small), Int64: \(big)")
Common Mistakes
  1. Assuming Int is always 32-bit; on modern platforms Int is 64-bit, matching the native word size.
  2. Overflowing a fixed-size integer type like Int8 and being surprised by a runtime crash instead of silent wraparound.
  3. Mixing Int and UInt (or Int and Double) in an expression directly instead of explicitly converting first.
Chapter Summary
  • Int is 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 like UInt.
  • 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.