Skip to content

Singleton Class in Swift

Platform Language License

Overview:

  1. Singleton is a design pattern that is very popular in development.

  2. Singletons are easy to understand.

  3. The singleton pattern guarantees that only one instance of a class is instantiated.

In Apple’s frameworks we have come across below singleton classes:

// Shared URL Session
let sharedURLSession = URLSession.shared

// Default File Manager
let defaultFileManager = FileManager.default
// Standard User Defaults
let standardUserDefaults = UserDefaults.standard

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

private init(){}

Above class is having by default internal initializer, its change to private. Now you can’t initialize your singleton class again.

SingletonExp

Let's grow together 🌱

Cheers 🍻