Singleton Class in Swift
Overview:
-
Singleton is a design pattern that is very popular in development.
-
Singletons are easy to understand.
-
The singleton pattern guarantees that only one instance of a class is instantiated.
In Apple’s frameworks we have come across below singleton classes:
There are times that you want to make sure only one instance of a class is instantiated and that your application only uses that instance. That’s the primary and only goal of the singleton pattern.
Example:
//MARK:- Location Manager
class LocationManager{
static let shared = LocationManager()
init(){}
//MARK:- Location Permission
func requestForLocation(){
print("Location Permission granted")
}
}
//Access the class with Singleton Pattern
LocationManager.shared.requestForLocation() //"Location Permission granted"
//Still you can access the class by creating instance
let location = LocationManager() //initialization class
location.requestForLocation() //Call function here
So we have to change the access level of initializer
Above class is having by default internal
initializer, its change to private
. Now you can’t initialize your singleton class again.
Let's grow together 🌱
Cheers 🍻