DEV Community

Ramdhas Munirathinam
Ramdhas Munirathinam

Posted on

Prevent Unauthorized Instantiation of a Singleton Class in Swift

In Swift, a Singleton is a design pattern that ensures that a class has only one instance and provides a global point of access to that instance. To prevent the creation of additional instances of a Singleton class, you can take a few steps:

Use a Private Constructor: Make the initializer (constructor) of your Singleton class private, so it can only be called from within the class itself. This will prevent external code from creating new instances of the class.

Provide a Static Property for Access: Create a static property (often called shared or sharedInstance) to provide a single point of access to the Singleton instance. This property will be responsible for creating and returning the single instance of the class.

Here’s an example of how to create a Singleton in Swift:

`class MySingleton {
    // Step 1: Make the constructor private
    private init() {
        // Initialization code here
    }

    // Step 2: Create a static property for access
    static let shared = MySingleton()

    // Add other properties and methods here
}
`

Enter fullscreen mode Exit fullscreen mode

With this implementation, you can access the Singleton instance like this:

let mySingleton = MySingleton.shared

No other instances of MySingleton can be created from outside the class because the constructor is private.

By following these steps, you can ensure that your Singleton class remains a true Singleton, with only one instance throughout your application.

_A sample code that demonstrates what happens if you try to create an instance of a Singleton class with a private constructor:
_

`class MySingleton {
    private init() {
        print("Creating a MySingleton instance.")
    }

    static let shared = MySingleton()
}

// Attempting to create a new instance
let instance1 = MySingleton()  // This will result in a compile-time error

Enter fullscreen mode Exit fullscreen mode

`

In this code, when you try to create a new instance of MySingleton using let instance1 = MySingleton(), you will receive a compile-time error because the constructor is private. The error message will look something like:

'init' is inaccessible due to 'private' protection level

This error prevents you from creating additional instances of the Singleton class, ensuring that only the shared property can be used to access the single instance of the class.

Top comments (0)