Describe the 'Singleton' design pattern and its use in iOS.
Instruction: Explain what the Singleton pattern is and provide examples of its use in iOS development.
Updated
Official answer
A singleton exposes one shared instance and restricts ordinary construction so callers use that instance. It can be useful for a genuinely process-wide immutable configuration or a carefully isolated service, but it introduces global lifetime and dependencies that can complicate tests and account/session separation.
This complete example is immutable and Sendable, so sharing it does not expose mutable unsynchronized state:
final class AppConfiguration: Sendable {
static let shared = AppConfiguration()
let maximumPreviewItems = 20
private init() {}
}
let first = AppConfiguration.shared
let second = AppConfiguration.shared
assert(first === second)
assert(first.maximumPreviewItems == 20)
Swift initializes a stored type property lazily on first access, once even with concurrent access. That protects initialization; it does not automatically protect later changes to mutable properties of the instance. A mutable service needs an actor, MainActor isolation when appropriate, or another consistent synchronization design. A singleton is per process and is not durable storage or a distributed coordination mechanism.
UserDefaults.standard is an example of a framework-provided shared default object. UserDefaults also allows other instances/suites, so that API does not mean only one UserDefaults object can exist. Similar “shared” conveniences should be assessed by their actual construction and ownership contract.
I would inject an interface into features that need the service, allowing a substitute in tests and explicit per-account state where necessary. Avoid storing private user data in an unbounded global cache or using a singleton merely to avoid passing a dependency.
Swift stored and type properties, Shared defaults object, Swift concurrency and isolation