Skip to the workspace
Pebellslearn by building
Swift Basics  ›  Lesson

Constants, Variables and Types

Swift Basics 12 minSwift values are declared with let when they never change and var when they must, and every value has one type that Swift usually infers.

ios / Constants, Variables and Types

Explore each scene at your own pace.

01 · The rule

The rule

Constants, Variables and Types

TrailLog stores a hike's name, distance, elevation gain and whether it is a favourite. Every one of those values has a type, and every one is either fixed or allowed to change. Swift makes you decide both up front, and that decision is most of what Swift basics is about.

The rule

Start with let; switch to var only when the value must change.

let declares a constant: once set, it can never be reassigned. var declares a variable that can.

let name = "Ridge Loop"        // String
let distanceKm = 8.5           // Double
var elevationGain = 420        // Int
var isFavourite = false        // Bool

elevationGain += 30            // fine: var
// name = "River Walk"         // error: cannot assign to a let

Swift is strongly typed: every value has exactly one type, fixed at compile time. You rarely write the type, because Swift infers it from the value: 8.5 is a Double, 420 is an Int. You can still write it when inference would pick the wrong thing:

let target: Double = 10        // 10 would otherwise be an Int

Swift never converts between number types for you. Mixing them is a compile error until you convert on purpose:

let pace = distanceKm / Double(elevationGain)

To build text, use string interpolation — put any value inside \( ) in a string:

let label = "\(name): \(distanceKm) km"   // "Ridge Loop: 8.5 km"

Why prefer let? A constant cannot be changed by some distant line of code, so it is easier to reason about, and the compiler warns you when a var is never mutated.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.