Singleton in Swift
Singleton is a pattern use for maintaining single instance of a class and also single reference of it’s object. It means that if there is a class Person then there can only be one instance and reference of a Person. Copying is not allowed.
final class Singleton{
static let sharedInstance = Singleton()
private init() {}
}final is important so that no other class can subclass singleton.
static let is used to make sure that it is accessible globally and anyone cannot change sharedInstance.
private — This ensures that no other class can instantiate or make new objects of class Singleton. If we do not use a private initializer, singleton class will create it’s own default public initializer.
An important thing to note is that
staticproperties and methods are lazy initialize by default meaning that it will not be instantiated until it is being called, therefore provides some optimization.It isn’t necessary to mark static properties with the
lazykeyword because the initializer of global variables and static properties are executed lazily by default. That's another benefit.
Advantages of Singletons:
- Convenience and easy to implement.
- Solve problem of single instance of a class.
- Everyone understands so new developers can easily get around it.
Disadvantages of Singletons:
- Misunderstood and misuse by developer community even experience one.
- Losing track where it used in project.
- Refactoring becomes tough in large projects.
- It is used for globals instead it should only be used for purpose of single instance of a class.
- Unit testing becomes impossible because any objects can have access and modify it.
- Order of the tests now matters
- Tests can have unwanted side effects caused by singleton
