Junior — Middle
Where are global variables usually declared and stored in a program?
sobes.tech AI
Answer from AI
Variables with global scope in iOS applications are usually declared outside classes and functions, at the file level (global scope), or in special singleton objects.
Most often, global variables are placed:
- In separate Swift files outside classes, so they are accessible throughout the module.
- In structures or singleton classes to control access and initialization.
Example of a global variable in Swift:
// Globals.swift
var globalCounter = 0
// Usage elsewhere
globalCounter += 1
Or singleton:
class Settings {
static let shared = Settings()
var userToken: String?
private init() {}
}
// Usage
Settings.shared.userToken = "abc123"
This approach helps avoid state management issues and improves code readability.