Combine Static Functions & Properties to Create Singleton Objects
Written by Team Kodeco
A singleton is a design pattern in which a class has only one instance, and provides a global point of access to that instance. Singletons can be useful for managing shared state or resources, such as database connections, network sockets, or shared configuration data.
In Swift, you can combine static functions and properties to create singleton objects. To create a singleton, you can define a class with a private initializer and a static property that holds a single instance of the class.
Here’s an example of a Settings class that implements a singleton pattern:
class Settings {
static let shared = Settings()
private init() {}
var fontSize: Double = 14.0
}
let settings = Settings.shared
settings.fontSize = 16.0
let anotherSettings = Settings.shared
print(anotherSettings.fontSize) // 16.0
In this example, Settings
has a private initializer, which means that it cannot be instantiated outside of the class. shared
is a static property that holds a single instance of Settings
. By making the initializer private, you prevent the class from being instantiated from outside of the class, ensuring that there is only one instance.
To access the shared instance, you use the Settings.shared
property. Both settings
and anotherSettings
refer to the same instance, so changing fontSize
in one instance also changes it in the other.
This demonstrates how you can use static functions and properties to create singleton objects in Swift, making it easy to manage shared state or resources that need to be accessible from multiple parts of your code.