iOS Swift singleton pattern
December 16, 2015

When people are switching from Objective-C, then most common question is:"How the hell do I do this with Swift?!". In particular - iOS Swift singleton pattern. Sometimes the answer is a just satisfying, though sometimes the way something is handled in Swift just makes you wonder "why so simple?".
Singleton patter is one of those "Why so simple" things.
Objective-C Style
Many people would go with
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!
}
}
Meh.
Swift style
And now just take a look at singleton implementation in Swift:
class Singleton {
static let sharedInstance = Singleton()
}
Clean, nice, awesome. Plus a good adivce I ran into at Hactor Matos' blog: make sure that your inits are private. This makes sure your singletons are truly unique and prevents outside objects from creating their own instances of your class. Since all objects come with a default public initializer in Swift, you need to override your init and make it private:
class Singleton {
static let sharedInstance = Singleton()
private override init() {}
}