DEV Community

Gamya
Gamya

Posted on Edited 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
✨ อัปเดตล่าสุด: gamya m/swift needs both integers and doubles - ประเด็นร้อน ✨ อัปเดตล่าสุด: gamya m/swift needs both integers and doubles - ประเด็นร้อน

Doubles store decimal numbers:

let flowerGrowth = 0.75
let animeRating = 4.5
✨ อัปเดตล่าสุด: gamya m/swift needs both integers and doubles - ประเด็นร้อน ✨ อัปเดตล่าสุด: gamya m/swift needs both integers and doubles - ประเด็นร้อน

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
✨ อัปเดตล่าสุด: gamya m/swift needs both integers and doubles - ประเด็นร้อน ✨ อัปเดตล่าสุด: gamya m/swift needs both integers and doubles - ประเด็นร้อน

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
✨ อัปเดตล่าสุด: gamya m/swift needs both integers and doubles - ประเด็นร้อน ✨ อัปเดตล่าสุด: gamya m/swift needs both integers and doubles - ประเด็นร้อน

Why? Because Double values can change:

var myDouble = 1.0
myDouble = 1.5
✨ อัปเดตล่าสุด: gamya m/swift needs both integers and doubles - ประเด็นร้อน ✨ อัปเดตล่าสุด: gamya m/swift needs both integers and doubles - ประเด็นร้อน

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)
✨ อัปเดตล่าสุด: gamya m/swift needs both integers and doubles - ประเด็นร้อน ✨ อัปเดตล่าสุด: gamya m/swift needs both integers and doubles - ประเด็นร้อน

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)