The Swift Singleton Pattern

Stefano Frosoni
If let swift = Programming!
2 min readJul 18, 2016

The Singletons pattern provide a globally accessible, shared instance of an object.

For most cases you don’t need a singleton in iOS (this can be abused to form poorly constructed code) but there are some cases in which it makes sense to have exactly one instance of a class. .

Apple uses this approach a lot. For example: UIApplication.sharedApplication(), NSUserDefaults.standardUserDefaults(), NSFileManager.defaultManager() all return a Singleton object.

In Objective-C, to ensure that only one instance of a singleton object is created, its initialization is wrapped in a call the dispatch_once function, which executes a block once and only once for the lifetime of an app.

In Swift, is just necessary to use a static type property, which is guaranteed to be lazily initialized only once, even when accessed across multiple threads simultaneously:

That’s it…THE ONE LINE SINGLETON!

The usage is: Singleton.sharedInstance

Since all objects come with a default public initializer in Swift, we need to override the init and make it private. This makes sure the singleton is truly unique and prevents outside objects from creating their own instances of this class. The Singleton shoudl also be final to prevent this to be subclassed (if a singleton need additional functionality, it should be encapsulated in an extension). So we need to add another line:

This is the final correct implemetation of the Singleton.

Thanks to Michael Ormonde for the “private init” suggestion.

I hope you find this article useful. Thanks for reading!

Follow me on Twitter

--

--