DEV Community

Gamya
Gamya

Posted on

Swift needs both Integers and Doubles

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
Enter fullscreen mode Exit fullscreen mode

Doubles store decimal numbers:

let flowerGrowth = 0.75
let animeRating = 4.5
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Why? Because Double values can change:

var myDouble = 1.0
myDouble = 1.5
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Swift forces you to choose how the conversion happens.


🌟 Wrap Up

  • Int is exact and safe for whole numbers
  • Double handles 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)