static let sharedInstance = Singleton() for a thread-safe, lazily initialized singleton in Swift 1.2+. The compiler automatically wraps static initialization in dispatch_once, making the old manual dispatch_once approach unnecessary and error-prone.Why this happens
Developers migrating from Objective-C often reach for dispatch_once to guarantee thread-safe singleton initialization. In Swift, however, dispatch_once is a C API that doesn’t map cleanly to Swift closures, leading to compiler errors like Cannot convert the expression's type 'Void' to type '()'. The root cause is a mismatch between the C function signature and Swift’s closure syntax, compounded by the fact that dispatch_once_t must be passed by reference (&token).
More importantly, Swift’s language guarantees make dispatch_once redundant. Since Swift 1.2, static properties and global variables are lazily initialized on first access, and the compiler emits the equivalent of dispatch_once around that initialization. This behavior is documented in Apple’s The Swift Programming Language guide: the lazy initializer for a global or static variable runs once, atomically, without any extra code.
How to fix it
1. Use a static class constant (recommended for Swift 1.2+)
The simplest, most idiomatic singleton in modern Swift is a single line:
final class Logger {
static let shared = Logger()
private init() {}
}
static letensures the instance is created lazily the first timeLogger.sharedis accessed.- The
finalkeyword prevents subclassing, which could otherwise break the singleton guarantee. - A
private init()blocks external instantiation.
No dispatch_once, no nested structs, no optionals — the compiler handles thread safety and lazy initialization automatically.
2. Nested struct workaround (only for Swift 1.1 or earlier)
If you are maintaining a codebase stuck on Swift 1.1 (Xcode 6.1), class constants don’t exist yet. The accepted workaround uses a nested struct with a static constant:
class LegacySingleton {
class var shared: LegacySingleton {
struct Static {
static let instance = LegacySingleton()
}
return Static.instance
}
private init() {}
}
Struct static constants have always been lazily initialized and thread-safe, even before class constants were added. This pattern is obsolete for any project on Swift 1.2+.
3. Avoid the manual dispatch_once pattern
The Objective-C style port looks like this and compiles, but it adds ceremony without benefit:
class OldSchoolSingleton {
class var shared: OldSchoolSingleton {
struct Static {
static var onceToken: Int = 0 // dispatch_once_t is Int in Swift
static var instance: OldSchoolSingleton?
}
dispatch_once(&Static.onceToken) {
Static.instance = OldSchoolSingleton()
}
return Static.instance!
}
private init() {}
}
Problems:
* Requires &Static.onceToken (inout parameter) — easy to forget.
* Forces an optional instance and a force-unwrap on return.
* dispatch_once is deprecated in favor of os_unfair_lock or Swift concurrency primitives for new code, but you don’t need either for singleton initialization.
How to prevent it
- Default to
static let shared = Type()for every new singleton. - Mark the class
finaland the initializerprivate. - Never use
dispatch_oncefor one-time initialization in Swift — the language does it for you. - If you need one-time setup logic (not just instance creation), use a private static
letwith a closure:
swift
private static let configuration: Config = {
let cfg = Config()
cfg.loadFromDisk()
return cfg
}()
FAQ
Is static let truly thread-safe on all Apple platforms?
Yes. The Swift runtime guarantees that the initializer runs exactly once, even when multiple threads access the property simultaneously. This matches the behavior of dispatch_once and works on iOS, macOS, watchOS, tvOS, and Linux.
Can I still use dispatch_once for other one-time setup tasks?
You can, but prefer Swift-native alternatives: a private static let with a closure for data initialization, or os_unfair_lock / NSLock for critical sections. dispatch_once is a C API and doesn’t integrate with Swift’s structured concurrency.
What about actor singletons in Swift 5.5+?
Actors provide isolation for mutable state, but a singleton instance doesn’t require an actor unless the singleton itself holds mutable state that needs synchronized access. For a simple shared service, static let remains the cleanest solution.
Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.
