let and var in Swift
Constants by default, mutation by request, types by inference.
// let binds a constant; var stays mutable. Types mostly infer.
let boat = "Kestrel"
var crew = 3
crew += 1
// Annotate when inference would guess wrong.
let handicap: Double = 0.92
let legNm = 4.5
print("\(boat) sails with \(crew) aboard")
print("Corrected leg: \(legNm * handicap) nm")
// Constants of any type, computed once at startup.
let courseMarks = ["pin", "windward", "leeward"]
print("Course has \(courseMarks.count) marks")
How it works
let boatcannot be reassigned;var crewcan, and+=updates it.handicap: Doublesteers inference where it would guess Int.- Collections infer too:
courseMarksis a[String].
Keywords and builtins used here
Doublecountletprintvar
The run, in numbers
- Lines
- 14
- Characters to type
- 437
- Tokens
- 82
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 70 seconds.
Step 2 of 3 in Values, step 2 of 27 in Language basics.