DevPrep

All topics › Programming basics

Static variable

Junior

Essence

A static variable belongs to the type, not an instance: one for all objects of the class/struct, alive until the program ends. In Swift that is static let / static var inside a type. The key thing to know: it is initialised not at program start, but lazily.

How it works in Swift

struct Config {
    static let value: Int = { print("computed"); return 42 }()
}
print("start")
print(Config.value)     // computed, then 42
print(Config.value)     // 42 — the initialiser does not run again

final class Analytics: Sendable {
    static let shared = Analytics()           // singleton: lazy and thread-safe
    @MainActor static var eventCount = 0  // Swift 6: error without isolation
    private init() {}
}

func nextID() -> Int {
    // static var n = 0        // error: static only inside a type
    enum Storage { nonisolated(unsafe) static var n = 0 }  // replacement idiom
    Storage.n += 1
    return Storage.n
}

The program prints start, computed, 42, 42 — "computed" appears once, and only after start.

Where it is used

What the interviewer looks for

"Initialised at program launch" is the wrong answer. Correct: lazily, once, thread-safely. Bonus — knowing why that gives you a free singleton and what Swift 6 changes.

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