Swift Integers ✨
When you work with whole numbers like 3, 42, or 1_000_000, you’re using integers in Swift (Int for short).
Integers represent whole numbers—no decimals.
🔹 Creating Integers
Creating an integer looks just like creating a string:
let powerLevel = 9000
var flowerCount = 12
Swift integers can be very large and can also be negative.
🔹 Readable Large Numbers
Big numbers are hard to read:
let petals = 100000000
Swift lets you use underscores to improve readability:
let petals = 100_000_000
Underscores are ignored by Swift—they’re just for humans.
🔹 Integer Math
Swift supports basic arithmetic operators:
let baseScore = 10
let bonus = baseScore + 5
let damage = baseScore * 2
let penalty = baseScore - 3
let halfPower = baseScore / 2
🔹 Updating Integers
Instead of rewriting values, you can use compound assignment operators:
var chakra = 10
chakra += 5
chakra *= 2
chakra -= 4
chakra /= 2
print(chakra)
These do the same thing, with less typing.
🔹 Useful Integer Checks
Integers have helpful built-in methods, like checking multiples:
let petals = 120
print(petals.isMultiple(of: 3))
You can even call it directly:
print(120.isMultiple(of: 3))
🌟 Wrap Up
Swift integers are powerful, safe, and easy to work with.
Top comments (0)