Variables and Constants
Declaring values with var and let, and how Swift infers types without you writing them out.
2 menit membaca
Swift has two ways to declare a named value: var for something that can change, and let for something that can't.
var score = 0
score = 10 // fine — score is a variable
let maxScore = 100
// maxScore = 200 // compile-time error — maxScore is a constantThat might look like a small distinction, but it's one of the most consequential habits in idiomatic Swift: default to let, and only reach for var when a value genuinely needs to change after it's created. The compiler will actually warn you if you declare something with var but never mutate it, nudging you back toward let.
Why prefer constants?
A value declared with let can't be reassigned, which means anyone reading the code — including future you — knows immediately that it's safe to reason about without tracking how it might change over time. It also lets the compiler catch accidental reassignment as an error instead of a silent bug.
let pi = 3.14159
let username = "grace_h"
let isLoggedIn = falseNone of these need to change once set, so let documents that intent directly in the code.
Type inference
Notice none of the examples above wrote out a type. Swift looks at the value on the right side of = and infers the type automatically — score is inferred as Int, pi as Double, username as String.
let temperature = 72.5 // inferred as Double
let city = "Toronto" // inferred as String
let isRaining = true // inferred as BoolYou can still write the type explicitly when it helps readability, or when there's no value yet to infer from:
let discount: Double = 0.15
var errorMessage: String? // no initial value, so the type must be statedOnce a type is set — inferred or explicit — it's fixed. Swift is statically typed, meaning city can never later be assigned a number; that's caught at compile time, not discovered when a user hits the bug in production.
Naming conventions
Swift uses camelCase for variable and constant names — maxScore, not MaxScore or max_score. Names should describe what the value represents, not its type (userCount, not userCountInt), since the type is already tracked by the compiler and rarely needs restating in the name.
Getting comfortable with let versus var is worth the repetition now — nearly every Swift codebase you read will lean heavily toward let, and understanding why will make the rest of this course's examples feel natural rather than arbitrary.