DevPrep

All topics › Programming basics

Local variable

Junior

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

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

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.

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store