Singleton in Swift

What is it? when and how to use it

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
    }()
}

Leave a Reply

Your email address will not be published. Required fields are marked *