Constants, Variables and Types
TrailLog stores a hike's name, distance, elevation gain and whether it is a favourite. Every one of those values has a type, and every one is either fixed or allowed to change. Swift makes you decide both up front, and that decision is most of what Swift basics is about.
The rule
Start with
let; switch tovaronly when the value must change.
let declares a constant: once set, it can never be reassigned. var declares a variable that can.
let name = "Ridge Loop" // String
let distanceKm = 8.5 // Double
var elevationGain = 420 // Int
var isFavourite = false // Bool
elevationGain += 30 // fine: var
// name = "River Walk" // error: cannot assign to a letSwift is strongly typed: every value has exactly one type, fixed at compile time. You rarely write the type, because Swift infers it from the value: 8.5 is a Double, 420 is an Int. You can still write it when inference would pick the wrong thing:
let target: Double = 10 // 10 would otherwise be an IntSwift never converts between number types for you. Mixing them is a compile error until you convert on purpose:
let pace = distanceKm / Double(elevationGain)To build text, use string interpolation — put any value inside \( ) in a string:
let label = "\(name): \(distanceKm) km" // "Ridge Loop: 8.5 km"Why prefer let? A constant cannot be changed by some distant line of code, so it is easier to reason about, and the compiler warns you when a var is never mutated.
The shortcut
For each value, ask two questions in order: "Will it ever change?" then "What type does the literal give me — is that the one I want?"
The date it was logged
Never changes after logging:
let loggedAt = Date(). Type inferred asDate.
The trap: writing var everywhere "just in case". The compiler will flag it, and every needless var is a place a bug can hide.
Drills
Answer fast — trust the rule.
What type does Swift infer for let gain = 420?
A hike's start date is set once and never changes. How should you declare it?
Why does let avg = distanceKm / hikeCount fail when hikeCount is an Int?
With let km = 8.5, which line produces the text 8.5 km?
Remember
- Start with
let; usevaronly for values that must change. - Swift infers types from literals — add an annotation when the inferred one is wrong.
- Trap: numbers never convert silently; wrap with
Double(...)orInt(...)yourself.
