Singleton in Swift
What is Singleton
Singleton is a design pattern that guarantees that only one instance of a class can be instantiated.
When to use Singleton
Use Singleton when you want to provide global point of access to a resource of a class, for example a class that provides sounds to your application. iOS frameworks are full of singleton examples like UserDefaults.standard or URLSession.shared
How to Create a Singleton
There are two ways for creating a singleton in Swift.
- First one is simply by creating a static type property
class MySingletonClass {
static let sharedInstance = MySingletonClass()
}
- The second way if you want to provide additional setup is by using a closure
class MySingletonClass {
static let sharedInstance: MySingletonClass = {
let instance = MySingletonClass()
// additional setup code
return instance
}()
}