The singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects.
Often the singleton is considered as an anti-pattern because it is frequently used in scenarios where it is not beneficial and introduces unnecessary restrictions in situations where a sole instance of a class is not actually required.
Anyway in some cases it is very useful and simplifies the logic of our software. For example Apple provides some functionalities as singleton, for example NSUserDefaults and NSNotificationCenter.
Writing a singleton in swift is really simple, for those coming from objective-c their singletons look like the following one:
and the usage
In swift, the same singleton will look like:
And the usage will be:
The private init declaration prevents others from using the default initializer for this class.