Mohammed R Ghate
2 min readJan 22, 2022

--

Difference between singleton and Singleton in Swift

Before starting to explore the difference let’s first talk about singleton first.

based on the Design patterns book (by gang of four) the definition of singleton is:

The singleton pattern is away to make sure that a class has only one instance and it provides a single point of access to it. The pattern specifies that the class should be responsible itself for tracking of its sole instance. It can further ensure that no other instance can be created by intercepting requests for creating new objects and provide a way to access the sole instance.

so let’s write some code to demonstrate the definition:

class Sample{  //1  
private init(){}
//2
private static let sample = Sample()
static func shared() -> Sample{
return sample
}
}let sample = Sample.shared()

First, by making init of the class to be private we ensure that the class can not be instantiated and we have only one instance by defining a method which is the only way to access the Class and use static so to make it type method. Sample class is a Singleton with a capital S. But in swift, we can define the access point much easier by using the combination of static and let:

class Sample{//1  
private init(){}
//2
static let shared = Sample()
}let sample = Sample.shared

In swift static let is lazy loaded and let is immutable so we are sure that the class can only have one instance.

Now let’s talk about the other version of singleton with lowercase s Actually, you already have worked with it when you were working with UIApplication and URLSession.

Although UIApplication has a shared property to access the shared object you also can create a new UIApplication. So based on the design patterns book apple has broken the rule to prevent instantiating a new object but this is the other version of singleton. Now let's create a new singleton:

class Sample{
static let shared = Sample()
}
let sample = Sample.shared
let newSample = Sample()

As you may find out the difference between singleton and Singleton is the ability to create a new object from the class, It is up to you to decide when to use Singleton or singleton. By the way, if you want to stick to the book you should not define your class as final and let the singleton be subclassed.

--

--