Singleton Class in Swift

The Singleton design pattern guarantees that only one object of a class will exist in a system.

// Creating a Singleton
// Only one instance of this class can be created
class CloudCodeExecutor {

    // Declare class instance property
    static let sharedInstance = CloudCodeExecutor()
    // Declare an initializer 
    // Because this class is singleton only one instance of this class can be created
    private init() {
        print("CloudCodeExecutor has been initialized")

    // Add a function
    func processCloudCodeOperation() {
        print("Started processing cloud code operation")

        // Your other code here

// Call function of Singleton class

// Call cloud code operation function again

// And again to see that class initializer was called only once

Leave a Reply

Your email address will not be published.