Zum Inhalt springen
KodeTrail

Camp 1 · Schritt 3 von 12

let and var

Constants first, variables when needed — Swift's core habit, and why Xcode itself nags you about it.

12 Min.+50 XPAuf Englisch angezeigt — Übersetzung ist unterwegs

Swift's two declaration keywords draw one line: can this value ever change?

let: constants

SwiftCloud-Run

let binds a value permanently. Reassignment is a compile error: "Cannot assign to value: 'altitude' is a 'let' constant" — with a suggested fix.

var: variables

SwiftCloud-Run

var allows change — counters, accumulators, anything genuinely mutable.

The Swift habit: let until proven var

Idiomatic Swift declares everything with let first and only promotes to var when the compiler proves mutation is needed. It's such core culture that Xcode literally warns: "variable was never mutated; consider changing to let."

Why care so much?

  • A let is a promise to readers: this won't shift under you
  • The compiler can optimize constants aggressively
  • Accidental mutation — a classic bug source — becomes impossible

The same const-first instinct you met in JavaScript and Dart; Swift just enforces it with the friendliest nagging in the business.

Checkpoint

let maxDepth = 30; maxDepth = 40 — what happens?

Checkpoint

You declared var total = 0 but never changed it. Idiomatic Swift says…