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:
- A static property
shared
is defined on theCalculate
class. This property is declared asstatic
which means it belongs to the class itself and not to any specific instance of it. - The
shared
property is initialized with an instance of theCalculate
class using the private initializerprivate init()
. Theprivate
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 theCalculate
class. - The
addTwoNumbers(first:second:)
method is defined on theCalculate
class, which simply returns the sum of two integers passed as arguments. - The
shared
property can be accessed from anywhere in the application by callingCalculate.shared
, which will always return the same instance of theCalculate
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