Turn from: Click to open link
From my short experience with Swift there is three approaches to implement the Singleton pattern, support lazy Initia Lization and thread safety.
These approaches might change or become redundant as the language matures.
GLOBAL constant
Let _singletonsharedinstance = Singleton()
Class Singleton {
class var sharedinstance: Singleton {
return _singletonsharedinstance
}
}
We use a global constant because class constants is not yet supported.
This approach supports lazy initialization because Swift lazily initializes global constants (and variables), and is Threa D Safe by virtue of a let .
Nested struct
Class Singleton {
class var sharedinstance: Singleton {
struct Static {
Static Let instance: Singleton = Singleton ()
}
return static.instance
}
}
Unlike classes, structs do support static constants. By using a nested struct we can leverage its static constant as a class constant.
Dispatch_once
The traditional objective-c approach ported to Swift. I ' d say it ' s no longer necessary to use this approach but I ' m putting it's here anyway as I find the differences in syntax I Nteresting.
Class Singleton {
class var sharedinstance: Singleton {
struct Static {
Static var oncetoken: dispatch_once_t = 0
Static var instance: Singleton? = Nil
}
Dispatch_once (&static.oncetoken) {
static.instance = Singleton ()
}
return static.instance!
}
}
Swift realizes three ways of Singleton pattern in a singleton mode