DevPrep

All topics › Programming basics

Global variable

Junior

Essence

A global variable is declared at the top level of a file, outside any type or function, and is accessible from anywhere in the module (with public, from other modules too). Where exactly in the file it sits does not matter.

How globals work in Swift

import Foundation

// Initialised lazily on first access, thread-safe
let apiBase = URL(string: "https://api.example.com")!

// Swift 6: `var launchCount = 0` — error: global is not concurrency-safe
@MainActor var launchCount = 0                 // main-actor access only
nonisolated(unsafe) var legacyFlag = false     // "I handle the races myself"

@MainActor func appDidLaunch() { launchCount += 1 }

Why global state is considered bad practice

Alternatives: static let constants inside a namespace type (enum Config { static let apiBase = ... }), dependency injection, @Environment in SwiftUI, an actor for shared mutable state. A singleton (static let shared) is still a global, but at least with lazy initialisation and a namespace.

What the interviewer looks for

Do you know about lazy, thread-safe initialisation (the common question "why is static let shared thread-safe?") and what Swift 6 does with global vars.

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