Skip to content

Instantly share code, notes, and snippets.

@tgnivekucn
Created July 17, 2022 11:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tgnivekucn/4c46443311f2ffbd178c43f5373b8066 to your computer and use it in GitHub Desktop.
Save tgnivekucn/4c46443311f2ffbd178c43f5373b8066 to your computer and use it in GitHub Desktop.
Singleton pattern in Swift
// lazy Singleton: create the singleton object when needed
// Note: Global constants and variables are always computed lazily
// ref: https://docs.swift.org/swift-book/LanguageGuide/Properties.html#ID263
class SingletonGreed {
static let shared = SingletonGreed()
private init() {}
}
class SingletonThreadSafe {
private static var shared: SingletonThreadSafe?
private init() {}
static func getInstance() -> SingletonThreadSafe {
if shared == nil {
synced(self) {
if shared == nil {
shared = SingletonThreadSafe()
}
}
}
return shared!
}
static func synced(_ lock: Any, closure: () -> ()) {
objc_sync_enter(lock)
closure()
objc_sync_exit(lock)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment