Skip to main content

Command Palette

Search for a command to run...

Swift: Singleton Pattern

Published
2 min read

In this article, we are going through a creational design pattern, Singleton.

What is Singleton?

A pattern is called Singleton when it satisfies the below conditions:

  1. Class should create its own single private instance.
  2. Class shouldn't allow creating instances from outside.
  3. Others can access the class, only through the instance created within the class.

Normally, this is how a singleton looks in any other language.

class User {
  // 1
  private let shared = User()

  // 2
  private init() { }

  // 3 
  static func getInstance() -> User {
    return shared
  }

}

//MARK:- USAGE
User.getInstance()

From the above code,

  1. You are creating the single private instance shared of the class User.
  2. You are adding the private access modifier to the init() method so that no other instance can be created by others.
  3. Exposing the instance - Creating the getter method getInstance and returning the privately initialized shared object, so that others could use this to access the properties inside the User class.

Alas, the Singleton is created, But there is a way to improve the above code. Since we are coding in Swift, You can declare the shared instance using the static property, so you don't need to have a separate method for exposing the instance. Here's the code for Swifty Approach.

class User {
  // 1
  static let shared = User()

  private init() { }
 }

 //MARK:- USAGE
User.shared

The only change that is performed in the above code is the private instance is changed to a static instance in order to achieve a swiftier approach.

Hope you enjoyed reading this, we can explore more about the design patterns in the following articles.

Happy Coding!!!

More from this blog

Rasik Blog

9 posts