Swift Singleton

In Swift, Singleton is a design pattern that ensures a class can have only one object. Such a class is called singleton class.

To create a singleton class, we need to follow some rule

1. Create a private initializer

An initializer allows us to instantiate an object of a class. And, making the initializer of a class restricts the object creation of the class from outside of the class.

class FileManager {
 
  ... 
  // create a private initializer
  private init() {
  }
}

// Error Code
let obj = FileManager()

Here, the initializer of the FileManager class is private. So, when we try to create an object of FileManager outside of the class, we get an error.

2. Create static type Singleton Object

In Singleton class, we create a single static type object of the class. Making the object static allows us to access the object using the class name.

class FileManager {
  
  // static property to create singleton
  static let fileObj = FileManager()
  ... 
}

// access the singleton 
let data = FileManger.fileObj

Here, we are accessing the fileObj object using the class name FileManager.


Example: Swift Singleton

class FileManager{

 // create a singleton
 static let fileObj = FileManager()

 // create a private initializer
private init() {
  
}

 // method to request file
func checkFileAccess(user: String) {

  // condition to check username
  if user == ("@programiz.com") {  

    print("Access Granted")
  }

  else {
    print(" Access Denied")
  }
}
}

let userName = "@programiz.com"

// access method
let file = FileManager.fileObj

file.checkFileAccess(user: userName)

Output

Access Granted

In the above example, we have created a singleton class FileManager. Since it is a singleton class, we have made the initializer private and created a static object named fileObj.

Notice the line,

var file = FileManager.fileObj
file.checkFileAccess(user: userName)

Here, we have accessed the object fileObj using the class name FileManager. We then accessed the method checkFileAccess().

Note: A design pattern is like our code library that includes various coding techniques shared by programmers around the world.


It's important to note that, there are only a few scenarios (like file managing, API requests) where singletons make sense. We recommend you avoid using singletons completely if you are not sure whether to use them or not. Learn more: What is so bad about Singleton?

Table of Contents

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges