Local variable
Essence
A local variable is declared inside a function, method, closure or block (if, for, do). It exists only while that block runs and is invisible outside it. It is the safest kind of state: nothing but the code next to it can change it.
How it works in Swift
- Scope is the nearest pair of braces. An inner block may declare a variable with the same name (shadowing);
if let x = xis an idiom built on the same principle. - Memory: usually the stack frame; freed automatically on return, no ARC needed for value types. If an escaping closure captures the variable, the compiler moves it to the heap (boxing) so it outlives the function.
letby default: the compiler warns when avaris never mutated. Immutable locals are easier to read and safe to pass into aTask.- Initialisation is required before the first read — the compiler enforces it (definite initialisation), so a "garbage" value like in C is impossible.
func total(of prices: [Double]) -> Double {
var sum = 0.0 // lives only inside this call
for p in prices {
let withTax = p * 1.2 // scope: the loop body
sum += withTax
}
return sum
} // sum and withTax no longer exist
func makeCounter() -> () -> Int {
var count = 0 // captured by the closure → moves to the heap
return { count += 1; return count }
}
let next = makeCounter()
print(next(), next()) // 1 2
Local vs global vs property
- Local — short lifetime, no races, no hidden dependencies.
- Property — lives as long as the instance; visible to all the type's methods.
- Global — lives for the whole program; in Swift 6 a mutable one needs isolation.
Rule: keep state in the narrowest scope where it is needed. If two methods need a variable, it is a property; if one does, it is a local.
What the interviewer looks for
Do you understand closure capture: count in the example above is the same variable on every call, not a copy, because the closure holds a reference to its box. This is the foundation of questions about [weak self] and capture lists.