Created
July 17, 2022 11:09
-
-
Save tgnivekucn/4c46443311f2ffbd178c43f5373b8066 to your computer and use it in GitHub Desktop.
Singleton pattern in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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