Why Swift Needs Both Integers and Doubles
Swift gives us different number types because numbers solve different problems.
The two most common ones are Integers (Int) and Doubles (Double)—and Swift keeps them separate on purpose.
🔹 Integers vs Doubles
Integers store whole numbers:
let petals = 12
let powerLevel = -9000
Doubles store decimal numbers:
let flowerGrowth = 0.75
let animeRating = 4.5
Both are numbers, but they behave very differently.
🔹 How Swift Chooses the Type
Swift decides the type based on the value you write:
let myInt = 1 // Int
let myDouble = 1.0 // Double
Even though both represent the number one, they are not the same type.
🔹 Why You Can’t Mix Them
This is not allowed:
let total = myInt + myDouble // ❌ Error
Why? Because Double values can change:
var myDouble = 1.0
myDouble = 1.5
Swift can’t safely add an integer to a decimal without risking loss of precision.
This is why Swift enforces type safety.
🔹 Explicit Conversion
If you want to combine them, you must be clear about it:
let total1 = Double(myInt) + myDouble
let total2 = myInt + Int(myDouble)
Swift forces you to choose how the conversion happens.
🌟 Wrap Up
-
Intis exact and safe for whole numbers -
Doublehandles decimals but isn’t perfectly precise - Swift keeps them separate to prevent bugs
It may feel strict at first, but this rule saves you from subtle bugs—just like a disciplined anime sensei 🌸✨
Top comments (0)