Singleton in Swift

Abhishek Kumar
Aug 31, 2018 · 2 min read

Singleton is a pattern use for maintaining single instance of a class and also single reference of it’s object. It means that if there is a class Person then there can only be one instance and reference of a Person. Copying is not allowed.

final class Singleton{
static let sharedInstance = Singleton()
private init() {}
}

final is important so that no other class can subclass singleton.

static let is used to make sure that it is accessible globally and anyone cannot change sharedInstance.

private — This ensures that no other class can instantiate or make new objects of class Singleton. If we do not use a private initializer, singleton class will create it’s own default public initializer.

An important thing to note is that static properties and methods are lazy initialize by default meaning that it will not be instantiated until it is being called, therefore provides some optimization.

It isn’t necessary to mark static properties with the lazy keyword because the initializer of global variables and static properties are executed lazily by default. That's another benefit.

Advantages of Singletons:

  1. Convenience and easy to implement.
  2. Solve problem of single instance of a class.
  3. Everyone understands so new developers can easily get around it.

Disadvantages of Singletons:

  1. Misunderstood and misuse by developer community even experience one.
  2. Losing track where it used in project.
  3. Refactoring becomes tough in large projects.
  4. It is used for globals instead it should only be used for purpose of single instance of a class.
  5. Unit testing becomes impossible because any objects can have access and modify it.
  • Order of the tests now matters
  • Tests can have unwanted side effects caused by singleton
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade