Skip to content

Instantly share code, notes, and snippets.

@congpc
Last active December 3, 2015 07:11
Get singleton instance by Swift
/*
* Way 1: Class constant
* This approach supports lazy initialization because Swift lazily initializes class constants (and variables), and is thread safe by the definition of let.
* Class constants were introduced in Swift 1.2. If you need to support an earlier version of Swift, use the nested struct approach below or a global constant.
*/
class SWManagement: NSObject {
static let sharedInstance = SWManagement()
}
/*
* Way 2: dispatch_once
* The traditional Objective-C approach ported to Swift. I'm fairly certain there's no advantage over the nested struct approach but I'm putting it here anyway as I find the differences in syntax interesting.
*/
class SWManagement: NSObject {
class var sharedInstance: SWManagement {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance: SWManagement? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = SWManagement()
}
return Static.instance!
}
}
/*
* Way 3: Nested struct
* Here we are using the static constant of a nested struct as a class constant. This is a workaround for the lack of static class constants in Swift 1.1 and earlier, and still works as a workaround for the lack of static constants and variables in functions.
*/
class SWManagement: NSObject {
class var sharedInstance: SWManagement {
struct Singleton {
static let instance = SWManagement()
}
return Singleton.instance
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment