Skip to content

Instantly share code, notes, and snippets.

@quinncnl
Forked from rgcottrell/gist:fdc7dd7cf5bc3ed61010
Last active August 29, 2015 14:27
Show Gist options
  • Save quinncnl/4765db56b5db4729c3d5 to your computer and use it in GitHub Desktop.
Save quinncnl/4765db56b5db4729c3d5 to your computer and use it in GitHub Desktop.
Thread safe shared instance "singletons" in Swift.
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!")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment