← thecodex.expert · The Codex Family of Knowledge
Swift

Variables and Types

Swift’s own official guidance is explicit: always start with let, and switch to var only once the compiler actually tells you a value needs to change.

Swift 6 let by default, var when needed Last verified:
Canonical Definition

let declares a constant, assigned exactly once; var declares a variable that can be reassigned freely. Both usually infer their type from the initializer (let age = 30 infers Int), though an explicit annotation (let age: Int) is used when no initializer is present yet or when clarity is genuinely helpful. The official Swift style guidance is direct: declare everything as let first, and only change to var if the compiler flags an actual reassignment as an error — treating immutability as the default, not an afterthought.

let vs var

Reassigning a let constant is a compile error, caught immediately — exactly the guarantee that makes let the safer starting point for anything that doesn't genuinely need to change.

Swiftlet_var.swift
let name = "Alice"      // constant — type inferred as String
var age = 30              // variable — type inferred as Int

age = 31                   // fine — age is a var
// name = "Bob"            // COMPILE ERROR: cannot assign to a let constant

Type inference and explicit annotations

An explicit annotation is required when there's no initializer to infer from, or when a wider type is genuinely intended (Double instead of the narrower Int Swift would otherwise infer from an integer literal).

Swifttype_annotations.swift
let count = 42            // inferred: Int
let price: Double = 20      // explicit — without this, 20 alone would infer as Int, not Double
var name: String            // explicit — no initializer yet, so annotation is required
name = "Alice"

Basic types and string interpolation

\() embeds any expression's value directly into a string — no manual concatenation or string-formatting calls needed for the common case.

Swiftbasic_types.swift
let count: Int = 42
let price: Double = 19.99
let isActive: Bool = true
let initial: Character = "S"

let message = "Count is \(count), price is \(price)"   // string interpolation
print(message)   // Count is 42, price is 19.99

Sources

1
Apple / Swift.org. The Swift Programming Language, "The Basics," docs.swift.org/swift-book.