typestar

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

  1. let boat cannot be reassigned; var crew can, and += updates it.
  2. handicap: Double steers inference where it would guess Int.
  3. Collections infer too: courseMarks is a [String].

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Values, step 2 of 27 in Language basics.

← Previous Next →