The Singleton Pattern in Swift

The Singleton pattern is a design pattern that ensures that only one instance of a class can be created, and provides a global point of access to that instance. In Swift, the Singleton pattern can be implemented using a static property and a private initializer, like this:

class Calculate { 

  static let shared = Calculate() 
  
  private init() { 
    // Initialize the singleton instance here. 
  } 
  
  func addTwoNumbers(first: Int, second: Int) -> Int {
    return (first + second)
  }
  
}


// Usage

class ViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()
    print(Calculate.shared.addTwoNumbers(first: 2, second: 3))
    // Output: 5
  }
    
}

In this example, the Calculate class is implemented as a singleton. Here’s how it works:

  1. A static property shared is defined on the Calculate class. This property is declared as static which means it belongs to the class itself and not to any specific instance of it.
  2. The shared property is initialized with an instance of the Calculate class using the private initializer private init(). The private keyword is used to prevent the instantiation of this class from outside the class, and hence it guarantees that there can be only one instance of the Calculate class.
  3. The addTwoNumbers(first:second:) method is defined on the Calculate class, which simply returns the sum of two integers passed as arguments.
  4. The shared property can be accessed from anywhere in the application by calling Calculate.shared, which will always return the same instance of the Calculate class.

In the ViewController, the viewDidLoad() method is called when the view is loaded, and it simply prints the sum of two numbers by calling the addTwoNumbers(first:second:) method on the shared instance of the Calculate class.

Overall, this singleton design pattern ensures that there is only one instance of the Calculate class in the application, and it can be accessed from anywhere using the Calculate.shared property.

Also read: The Observer Pattern in Swift


Posted

in