Singleton pattern — Swift

BN
iOS World
Published in
1 min readFeb 3, 2023

The Singleton pattern is a design pattern that restricts the instantiation of a class to only one instance, while providing a single point of access to that instance for all other objects. It is often used to ensure that there is only one instance of a class that manages a shared resource, such as a database connection or network socket.

Here’s a basic implementation of the Singleton pattern in Swift:

class Singleton {
static let shared = Singleton()
private init() {}
}

In this example, the shared property is a static constant that returns the single instance of the Singleton class. The init method is marked as private to prevent other objects from creating instances of the Singleton class. This ensures that there is only one instance of the class that can be accessed through the shared property.

How to prevent the creation of multiple instances?

The use of a private init method in the Singleton pattern is to prevent the creation of multiple instances of the class. The Singleton pattern requires that there be only one instance of the class, and by making the initializer private, it ensures that no other part of the code can create an instance of the class.

By marking the initializer as private, you prevent other objects from creating an instance of the class and guarantee that the only instance of the class is the one returned by the shared property. This is essential for enforcing the constraint that there be only one instance of the class.

--

--