Singleton Pattern — Swift

BN
iOS World
Published in
1 min readJan 17, 2023
Photo by Thomas Renaud on Unsplash

Singleton is a design pattern that ensures a class has only one instance and provides a global access point to this instance

To implement a singleton, you typically use a private init method to prevent other instances of the class from being created, and a shared instance property that returns the single instance of the class.

Implement a singleton class:

class MySingleton {
static let shared = MySingleton()
private init() {}
var value: String?
}

“MySingleton” is the name of the singleton class. Creates a shared instance of the class, which can be accessed from anywhere in the application using “MySingleton.shared”.

The private init line makes the initializer private, so that it can only be accessed within the class. This prevents other parts of the application from creating new instances of the class.

Get the value of the singleton like this:

MySingleton.shared.value = "Hello"
print(MySingleton.shared.value) // prints "Hello"

--

--