Sharing a state using Singleton
There are two questions that interviewers love to ask:
- “How do we create a Singleton?”
- “Is it good to have singletons in our app?”
The first question is technical, but the second one is tricky.
Let’s start with the definition of a Singleton.
What is a Singleton?
In the Singleton design pattern, there is only one instance of a class that can be globally accessed through a static
property. It is often used to manage shared resources or states in a program where multiple instances could cause issues with synchronization or consistency. To implement a Singleton, a class typically has a private constructor and a static method or property that returns the single instance of the class.
In Swift, it is simple to create a Singleton. We use a static property for that task:
final class MySingleton { static let shared = MySingleton() private init(...