Singleton in Swift 3

Henry Chan
2 min readMar 11, 2017

--

What is a Singleton?

Singleton is a design pattern where an object can be instantiated exactly only once within your application. There is only one copy of this object, and it is shared and used by any other object globally. The sole purpose of creating a singleton is to allow you to access it’s shared properties and methods, and making it globally accessible. This design pattern is useful when you want to only create one instance of an object. Let’s look at some some examples that are familiar to us but is exactly a singleton:

  • sharedURLSession
  • defaultFileManager
  • standardUserDefaults

Implementing Singleton

class Singleton {
static let sharedInstance = Singleton()
}

This one line code is all there is to implement a singleton. We put static because it is a type property, and it’s functionality is to create only one instance of an object and prevents its methods from being overridden. Using let will guarantee that sharedInstance ‘s value will not change.

A better approach

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

There is a few problem with how we implemented the singleton the first time. First is that we need to ensure that our singleton cannot be modified or subclasses by using the final keyword. Second is that we need to prevent other objects from creating their own instances of the singleton class by using private init . 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.

I hope this brief introduction to implement singleton has been somewhat helpful. Thanks for tuning in once again! 😎

--

--