Swift logo

Swift: how to create a Singleton pattern

By

in

What is a Singleton?

A singleton pattern guarantees that only one instance of a class is initialized and available from different points of an app.

Some examples are already available in Apple’s frameworks:

// Shared URL Session
let sharedURLSession = URLSession.shared

// Default File Manager
let defaultFileManager = FileManager.default

// Standard User Defaults
let standardUserDefaults = UserDefaults.standard

How to define a Singleton

Often a static constant is used to adopt the Singleton pattern. To do that the reference to the shared instance is stored inside a static constant. In addition, the initializer is private and therefore hidden:

class NetworkManager {
    static let sharedInstance = NetworkManager()

    private init() { }

    func doSomething() {
        // ...
    }
}

By making the initializer method private, it’s guaranteed that no other instance of this class can be created. It would also be possible to move the static constant outside the class, but then the initializer might be accessible and that’s not what we want.

To access our NetworkManager instance just call:

NetworkManager.sharedInstance.doSomething()
NetworkManager.sharedInstance.doSomething()

This approach allows to use always the same instance, even in different points of the app.



Comments

Leave a Reply

Your email address will not be published. Required fields are marked *