tezvyn:

Variables and Constants in Swift

AI-drafted, machine-checkedSource: docs.swift.orgbeginner

Swift has two ways to store a value: var declares a variable you can reassign later, and let declares a constant whose value is set once and can never change, and Swift's convention is to default to let unless you have a specific reason to need var.

WHY IT EXISTS Early languages made every variable mutable by default, which meant a value could change anywhere in a large codebase, and tracking down where and why it changed became a real source of bugs. Swift, like several modern languages, treats mutability as something you should opt into deliberately rather than get by default, so it gives you two distinct keywords instead of one.

THE MENTAL MODEL Think of let as writing in permanent marker and var as writing in pencil. Once you write a value with let, it is fixed on the page for good, so anyone reading your code later can trust it never changed. var means the value might get erased and rewritten later, so a reader has to stay alert to that possibility everywhere the variable is visible.

HOW IT WORKS Both var and let bind a name to a value with type inference, so let age = 30 and var age = 30 both infer an Int. The difference is enforced entirely at compile time: the compiler tracks whether a let bound name is ever assigned to more than once, including inside initializers, and refuses to build if it finds a second assignment. A let value does not have to be set at the point of declaration, it can be assigned once later, for example inside an if or an init method, as long as every code path guarantees exactly one assignment before use. var carries no such restriction, and Swift also lets you mark a var as private(set) so other files can read it but only the owning type can reassign it.

WHEN IT MATTERS It matters constantly in day to day Swift, because defaulting to let makes intent explicit: if you see var in a diff, you immediately know that value is expected to change somewhere. The footgun for beginners is declaring everything var out of habit from other languages, which both defeats compiler optimizations Swift can make for immutable values and hides which parts of your code actually depend on mutation.

ONE CONCRETE EXAMPLE A SwiftUI view model has let apiKey holding a value read from configuration once at init and never touched again, alongside var currentPage that the app increments each time the user scrolls to load the next page of results, making it obvious at a glance which property is fixed configuration and which one the app actively updates.

Read the original → docs.swift.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.