Singleton Class in Swift. Code Example.

The below Swift code example demonstrates how to implement the Singleton Design Pattern in Swift. Singleton Design Pattern guarantees that only one Object of a class exists in the system even if a developer attempts to create multiple instances of it.

Singleton Class example in Swift

// Creating 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 a singleton only one instance of this class can be created
    init() {
        print("CloudCodeExecutor has been initialized")
    }

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

        // Your other code here
    }
}

Try calling the processCloudCodeOperation() function multiple times and you will see that the initializer of the above class is called only once which means that only one instance of CloudCodeExecutor class was created and only one object of CloudCodeExecutor class exists in the system.

CloudCodeExecutor.sharedInstance.processCloudCodeOperation()
CloudCodeExecutor.sharedInstance.processCloudCodeOperation()
CloudCodeExecutor.sharedInstance.processCloudCodeOperation()

The output of calling processCloudCodeOperation() function multiple times is shown on the image below.

Singleton Design Pattern example in Swift

If you are interested to learn more about Swift and how to build mobile apps for iOS platform with Swift programming language, have a look at the list of video courses below. Those are some of the best online video courses on building iOS apps with Swift you can find on the internet.


Leave a Reply

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