Integers, Floats and Doubles
Sprout counts streak days and measures minutes spent. "4 days" and "12.5 minutes" look alike on paper, but they are different kinds of number, and choosing the wrong one gives you either a compile error or a quietly wrong answer.
The rule
Counted things are
Int; measured things areDouble.
Int holds whole numbers, positive or negative: days in a streak, habits in a list, check-ins this week. On today's 64-bit devices it reaches past nine quintillion either way, so you rarely think about its size.
let streak = 4
let totalCheckIns = 1_250 // underscores are only for readabilitySwift also has sized and unsigned integers such as Int8 (-128 to 127) and UInt8 (0 to 255), used mostly when talking to files or hardware. For everyday code, use Int.
Double holds numbers with a fractional part: minutes, distances, percentages. It keeps about 15 significant digits. Float is a smaller cousin with about 6 digits; use it only when an API asks for it. A literal with a decimal point is inferred as Double.
let minutesRead = 12.5 // Double
let progress: Float = 0.8 // Float, because we said soTwo behaviours to know:
- Integer division drops the fraction.
7 / 2is3, not3.5. DivideDoubles to keep it:7.0 / 2.0is3.5. - Overflow stops the program. If an
Int8holding 127 has 1 added at runtime, Swift crashes on purpose rather than wrapping to -128. A wrong number is worse than a stop.
Floating-point values are close approximations: 0.1 + 0.2 == 0.3 is false, because neither side is stored exactly.
The shortcut
Ask "could this ever be half?" Half a streak day makes no sense, so Int. Half a minute does, so Double. Then glance at every /: if both sides are Int, expect the fraction to vanish.
Choose the types
Days read: 4, a count, so
Int. Total minutes: 90, which could be 90.5 another week, soDouble.
Drills
Answer fast — trust the rule.
What is the value of 7 / 2 when both are Int?
Which type fits "minutes spent meditating today"?
What type does Swift infer for let x = 1_000?
What is the result of 0.1 + 0.2 == 0.3 with Doubles?
An Int8 variable holds 127 and your code adds 1 while the app runs. What happens?
Remember
- Counted things are
Int; measured things areDouble. - Ask "could this ever be half?", then check every
/between twoInts. - Overflow stops the program; decimals are approximate.
