By Nate Birkholz December 16, 2014

Singletons and Swift

*Singletons are a widely-used pattern in iOS development. Even Apple uses them in its own APIs, so you know they are legit! Yet despite the official approval from our friends in Cupertino, the singleton pattern is still widely debated on the interwebs. Nate, a recent graduate from our iOS Development Accelerator, does a great job explaining the pattern, its pros and cons, and how to implement a singleton in Swift.* ##### –Brad Johnson, iOS Development Accelerator instructor

First and Only

In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object.1

That definition confused and intimidated the heck out of me at first. However, as I write increasingly robust and complex software, it becomes very clear. I hope I can help you understand singletons in principle and how to easily make them in Swift.

Getting Started with Singletons

First off, let’s decode the definition. In any program, you are launching instances of different classes all the time. Each instance of a class is an object, a package of code or any collection of data that you are going to use. Instantiation generally means adding an instance of the object to memory by executing the code that defines it.

A singleton therefore is put into memory and can be accessed at any time without having to be re-instantiated on demand. This means that there will only ever be one instance of the singleton in memory at any time. In iOS under Swift, the AppDelegate meets these criteria itself, and some people use it to keep objects alive. This seems a reasonable choice, but it can also clutter up the AppDelegate and it can obscure some of the functionality of your code.

As mentioned previously, the issue I had with zombies was the example in my classwork that helped me actually understand not just how singletons worked, but more importantly why I might use them. I needed to access the animation delegate controller I had written, but it could be called when it had just been removed from memory, and that would crash the app.

Making It So

So how do we accomplish this? There are a lot of posts scattered around the Internet that debate a few similar methods in Swift, but the pattern leading the pack appears to be the following:

After you declare the class for your singleton object, add the following code:

class var sharedInstance : ObjectClassName {
  struct Static {
    static let instance : ObjectClassName = ObjectClassName()
  return Static.instance

This creates a class variable that holds a structure, which itself contains a static constant reference to the class. By declaring the static keyword in a struct, the instantiation will thereby be called on the type itself, instead of locally to the object referencing the struct. This little bit of trickery uses dispatch_once behind the scenes, as a constant is thread-safe, and has lazy instantiation that will only be created when first needed. Objects can safely reference the singleton and needn’t re-instantiate it every time.

To add the reference to the singleton to any object in your app, add the following constant to the properties of the object:

let objectClassName = ObjectClassName.sharedInstance

That object can then access the singleton methods and variables using the self.objectClassName property. For example, if the singleton had a function like:

getAValue(input: Int!) -> Int!

you could call:

var variable = self.objectClassName.getAValue(myLocalValue)

A Lasting Controversy

The singleton pattern is not always welcome, however, and to many developers is even controversial. Many people consider it a crutch and overused, and there are concerns about a singleton obscuring important relationships in your code. Some people even consider it an “anti-pattern,” or a common practice that is actually counterproductive in general use.

Miško Hevery at Google has a great article about the pitfalls of using the singleton pattern. Certainly in many professional contexts, singletons could be contrary to the design philosophy or the approved coding patterns, as well as being a poor choice. I’m sure passing your data well and traceably and instantiating your objects on demand is a better solution in many cases.

The above method of singleton creation does leave clear markers in your code, however, as you have to instantiate the reference in the properties of every object. The scope of the projects I am currently developing makes it a reasonable choice in certain cases. For example, declaring a singleton animation delegate to handle a switch case of ViewController transitions was my solution to the zombies issue. Choose wisely and always make sure you are coding to project standards. For the time being, I am happy to have the ability to guarantee the life of an object and its variables. I look forward to understanding more about the structural cases where singletons are the right choice, and where they aren’t.

Have fun, write code!