Last active
May 24, 2023 21:57
-
-
Save rgcottrell/fdc7dd7cf5bc3ed61010 to your computer and use it in GitHub Desktop.
Thread safe shared instance "singletons" 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
class Singleton { | |
class var sharedInstance: Singleton { | |
struct Static { | |
static var token: dispatch_once_t = 0 | |
static var instance: Singleton! | |
} | |
dispatch_once(&Static.token) { | |
Static.instance = Singleton() | |
} | |
return Static.instance | |
} | |
init() { | |
println("Init the Singleton!") | |
} | |
} | |
// | |
// UPDATE | |
// | |
// Static variables in a struct are lazily initialized, so there's no need for the dispatch once. | |
class Singleton { | |
class var sharedInstance: Singleton { | |
struct Static { | |
static let instance: Singleton! = Singleton() | |
} | |
return Static.instance | |
} | |
init() { | |
println("Init the Singleton!") | |
} | |
} | |
// Alternatively, a global variable, which is also lazily initialized, could be used to store the shared instance. | |
// A class method could optionally be added to provide a more object-oriented access to the shared instance. | |
let SingletoneSharedInstance: Singleton = Singleton() | |
class Singleton { | |
class var sharedInstance: Singleton { | |
return SingletoneSharedInstance | |
} | |
init() { | |
println("Init the Singleton!") | |
} | |
} |
Hi, what part of this makes it thread safe?
@ilandbt Swift initialize global variables (line 40) in an atomic way when they are first accessed :)
In Swift 3.0, you can simplify things even further:
class Singleton {
static let sharedInstance = Singleton()
private init() { }
}
Hi, what part of this makes it thread safe?
True! :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think its worth mentioning one-liner singleton pattern like from here since this gist is topmost in google search