Type Annotations and Type Inference
Sprout's daily goal was let dailyGoal = 2, meaning two hours. Then someone asked for "one and a half hours" and dailyGoal = 1.5 would not compile. The value had been given a type without anyone writing it down. Knowing how Swift picks types, and when to state one yourself, stops these surprises.
The rule
Swift guesses the type from the value; annotate when the guess is wrong.
Every constant and variable has exactly one type, fixed forever. Swift can work it out from the first value, which is type inference:
let habitCount = 3 // Int
let dailyGoal = 1.5 // Double
let habitName = "Read" // String
let isDoneToday = false // BoolA type annotation states the type yourself, with a colon after the name:
let dailyGoal: Double = 2 // 2 becomes 2.0, a Double
var reminderNote: String // no value yet, so the type is required
var morning, evening: Int // both are IntRead the colon as "of type": dailyGoal, of type Double, equals 2.
You need an annotation in two situations:
- No starting value. Swift has nothing to infer from.
- The inferred type is not the one you want. A whole-number literal like
2becomesInt; a literal with a decimal point becomesDouble. If you want aDoublefrom2, or aFloatat all, say so.
Otherwise, leave it out. Swift code is usually lighter without annotations, and the type is still just as fixed.
The shortcut
Look at the first value and read off its type: no dot means Int, a dot means Double, quotes mean String, true/false means Bool. If that answer is not what the value will need to hold later, add an annotation.
Read the first value
let dailyGoal = 2has no decimal point, so Swift infersInt.
Annotations do not make Swift "more typed". Inferred or written, a type never changes after the declaration.
Drills
Answer fast — trust the rule.
What type does Swift infer for let minutes = 25?
Which declaration MUST have a type annotation?
After var streak = 4, what happens with streak = "five"?
In var morning, evening: Double, what type is morning?
Remember
- Swift guesses the type from the value; annotate when the guess is wrong.
- No dot is
Int, a dot isDouble, quotes areString, true/false isBool. - Inferred or annotated, a type never changes after the declaration.
