Swift Singleton

by Kris Gellci

Just 24 hours after the announcement of Swift, I was bugging Apple Engineers on how to implement the singleton pattern.  The solution was much simpler than the Objective-c implementation. Let’s take a look at a simple singleton implementation in swift.


let sharedExample = Example()

class Example {
    var number = 0
}

The very first line of code is the bare minimum you need to have a shared instance of the class. we are using let in order to declare a constant.  The line is outside of the class and thus it is global.  It is being set to Example() but not right off the bat.  Here is the beauty of Swift.  The constant sharedExample will only be set once you call it.  This means that it is lazy loading by default and will not take up memory as soon as you run the code.

Now let’s look at how we would access this shared instance.


sharedExample.number = 5

The above line is essentially the equivalent of the following line in Objective-c


[Example sharedExample].number = 5

So to recap what we have learned so far, we have replaced the following Objective-c implementation with one line of code in Swift.


+ (id)sharedExample {
    static Example *shared = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shared = [[self alloc] init];
    });
    return shared;
}

How exactly is this possible you might wonder? It is simple. In Swift, global variables are loaded lazily, thread safe, and allocated only once no matter how many times you call them, which is pretty much the gist of what the singleton pattern is. There are people who will want to stick to the Objective-c conventions and call a method to return a shared instance, that is fine.  This post is the simplest implementation of the singleton pattern in swift. As the goal of swift is to make code shorter, and easier to understand, this is a short and easy to understand implementation of the singleton pattern in Swift.

 

Edit: I decided it would be a good idea to show another way to implement the singleton pattern in swift.  Consider the following code:


class Example {
    class var sharedInstance : Example {
        struct Singleton {
             static let instance = Example()
        }
        return Singleton.instance
    }

    var number = 0
}

Above is a great way to implement the singleton pattern but might be a bit confusing to first time swifters or programmers so lets run through it real quick. Essentially what we are doing is wrapping the shared instance or the single living soul in the class itself so the format for grabbing a reference to that one living object would be cleaner.

First we are creating a class variable which is basically something you can access without having to instantiate the class, also called a computed property. Inside of that class variable we have a struct which is wrapping a static constant named instance. The static portion of the statement makes it so this object only exists once, hence the single part of singleton. The let part as stated earlier in the post makes it a constant. Now why is it wrapped in a struct? Well it is basically a trick you can use since you can not have a static in a computed property, but you can in a struct, and you can have a struct in a computed property. To wrap it all up, the computed property is returning the static constant which is in the struct. Like before, it is only allocated once and only when you first call it!

So how exactly do we call it? A little bit different than before but this is where the benefit of using this format comes in.


Example.sharedInstance

As you can see, it is tied to the class and is closer to the objective-c way that we showed earlier.

Advertisements