In a Swift executable, when does a global constant's initializer run, and why can reading a main.swift top-level constant from another file go wrong?
answer
- first access, not launch
- exactly once, even across threads
- main.swift runs top to bottom
- no lazy keyword on globals
basics
~20 sA global declared in an ordinary source file is initialized lazily, exactly once, on first access. main.swift's top-level code instead runs in statement order, so another file reading one of its constants before that line executes sees uninitialized storage.
solid answer
~40 sGlobals in an ordinary source file are initialized on first access, not at launch. The runtime runs each initializer exactly once, even if threads race on that first access, so no `lazy` keyword is needed (`'lazy' cannot be used on an already-lazy global`). `main.swift` is different: its top-level code is the program's entry point and runs from top to bottom, so its declarations are initialized when execution reaches them. A function in another file that reads such a constant before that line has run is not diagnosed, and it reads storage that has not been initialized yet; a test build that did so with a `String` crashed. Separately, in Swift 6 language mode a mutable global `var` is an error unless it is isolated, for example to the main actor.
code
swift · 7 lines// Config.swift: an ordinary source file, not main.swift
func loadTaxTable() -> [String: Double] {
print("loading tax table")
return ["standard": 0.2, "reduced": 0.05]
}
let taxTable = loadTaxTable() // global: initialized lazily, oncego deeper
Recall that a global is declared outside any function and is visible across the module, and that its initializer runs the first time code uses it.
Explain lazy once-only initialization of globals, why lazy is redundant on them, and how main.swift top-level code differs by running in order.
Diagnose the undiagnosed crash from reading a main.swift constant early, know where a slow global initializer lands in a profile, and handle the Swift 6 mode error for mutable globals.
Set a rule for global state: constants of Sendable types in ordinary files are fine, mutable globals need an owner or an actor, and main.swift should only start the program.
## Global and local scope A **global** constant or variable is declared outside any function, type or closure. By default it is visible to every file in the module. A **local** one lives inside a function, method or closure and exists only while that code runs. Swift initializes the two very differently: | | Ordinary source file global | `main.swift` top-level declaration | Local | |---|---|---|---| | When the initializer runs | On first access | When execution reaches the line | When execution reaches the line | | Runs at most once | Yes, even across threads | Yes, it is a single pass | Once per call | | Must have a value at declaration | Yes, for a `let` | No | No | ## Globals are lazy, and safely so The Swift book states it directly: global constants and variables are always computed lazily, like a lazy stored property but without the `lazy` modifier, while local ones never are. In practice: 1. The program starts; nothing has computed `taxTable` yet. 2. The first code that reads `taxTable`, from any file, triggers its initializer. 3. The runtime's `swift_once` mechanism guarantees the initializer has run exactly once by the time that access returns, so two threads touching the global first at the same moment do not run it twice. 4. Every later access reads the stored value directly. Writing `lazy` in front of a global is therefore an error: `'lazy' cannot be used on an already-lazy global`. Stored `static` properties of types follow the same once-only, first-access rule; they are covered with type properties. Laziness has a practical cost to remember: an expensive global initializer, such as parsing a large table, runs at whatever moment first touches it, which may be in the middle of the first checkout rather than at launch. ## main.swift is different An executable has exactly one entry point, and a `main.swift` file is one form of it. Its top-level statements are **executable top-level code**: they run from top to bottom when the program starts, and the constants declared there are initialized when execution reaches their line, not lazily. That creates a trap the compiler does not catch: - `main.swift` calls `describeStore()` on its first line and declares `let storeName = "Corner Shop"` on the second. - `describeStore()` lives in another file and interpolates `storeName`. - The program compiles in Swift 5 and Swift 6 mode without any diagnostic, and the first call reads `storeName` before it has been initialized. A test build of exactly this crashed with a segmentation fault. The fixes are simple: declare shared values in an ordinary source file, where they are lazy and safe, or make sure `main.swift` initializes them before calling any code that reads them. A global `let` in an ordinary file must have its value on the declaration line (`global 'let' declaration requires an initializer expression`), which removes the ordering question altogether. The trap only exists when a program has executable top-level code. An app or a command-line tool whose entry point is a type marked `@main` has no `main.swift`; every file then holds only declarations, and every global in it is lazy. That is one reason many teams keep `main.swift` to a few lines that start the program, or replace it with `@main`. ## Mutable globals in Swift 6 language mode Laziness makes the first initialization safe, but not later writes. In Swift 6 language mode, a global `var` such as `var receiptsPrinted = 0` is rejected: ``` error: var 'receiptsPrinted' is not concurrency-safe because it is nonisolated global shared mutable state ``` The compiler's notes suggest converting it to a `let`, isolating it to `@MainActor`, or opting out when an external lock protects it. A module built with default main-actor isolation does not report it, because the global is then main-actor isolated. In Swift 5 mode the same code compiles silently. The isolation rules are covered with data-race safety; for this question, the point is that a global `let` of a `Sendable` type is the shape that stays valid in both modes. ## Key points - Globals in ordinary files: lazy, once, thread-safe first initialization. - `main.swift` top level: eager, in order; reading ahead from another file is undiagnosed. - Locals: never lazy. - Swift 6 mode: a mutable global `var` needs isolation.
- Is the lazy initialization of a Swift global safe when two threads access it first at the same time?Yes. Globals are initialized through the runtime's `swift_once`, which guarantees the initializer has run exactly once by the time any first access returns. Static stored properties have the same guarantee. That makes the first initialization safe; later writes to a global `var` are a separate problem, which Swift 6 language mode reports as an error.
- How would you fix a Swift 6 mode error on a global var counting printed receipts?Prefer removing the global state: make it a `let`, or move the counter into a type that owns it. If it must stay global, isolate it, for example with `@MainActor`, so every access goes through the main actor. Opting out of the check is only acceptable when an external lock really protects every access, and those isolation tools are covered with data-race safety.
- Saying globals are all initialized at launch, before main.swift runs
- Marking a global lazy to defer its work
- Treating a main.swift top-level constant like a lazy global
- Believing a global initializer may run twice under a thread race
- Expecting the compiler to catch a read of a not-yet-initialized main.swift constant
- Claiming Swift 5 mode rejects every mutable global var
Assumes Swift 6.4; lazy once-only global initialization holds in every release, while the error for a nonisolated mutable global var applies in Swift 6 language mode only.