Static variable
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
- Lazy, thread-safe initialisation: the value is computed on first access, exactly once, under
swift_once. That is whystatic let shared = Service()is a correct thread-safe singleton with nodispatch_once. staticvsclass:static varcannot be overridden in a subclass;class varcan, but only as a computed property (there are no storedclass vars).- No local statics: Swift cannot declare
static varinside a function the way C can. The idiom is a nested storage type. - Swift 6: a
static varis global mutable state, and without isolation (@MainActor) ornonisolated(unsafe)it is a compile error.static letis allowed when the type isSendable.
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
- Constants and namespaces:
enum Constants { static let pageSize = 20 }. - Singletons and caches (
static let shared). - Caching expensive objects:
static let formatter = DateFormatter()— created once instead of on every call.
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.