Singletons in Swift

In this post, I will demonstrate one particular way of creating singletons in Swift. But, before starting, let me just say: Swift is a very powerful programming language that allows developers to construct the same functionality in multiple ways. Therefore, the following example is just one way of building a singleton in Swift.

Generally, I discourage the use of singletons, as instantiating an object that will last forever is not good design. Instead, I prefer letting ARC do the memory management and letting ARC decide when to release an object or keep it alive. Additionally, there’s always an alternative way to build what you are trying to do with a singleton.

Nonetheless, despite my recommendations, I will demonstrate a way of building a singleton or a shared object in Swift, just in case you absolutely need one.

Let’s suppose that you need a shared instance of a class Monitor to continuously monitor the status of a running algorithm in your application. The Monitor class will be a subclass of NSObject and you want to instantiate this class only once. Here’s how to build this class in Swift:

In the above source code, first, I created a class Monitor subclassing NSObject. The class contains a static type  sharedMonitor. But, how can you use it? Well, suppose you need to reference this singleton from another object. You can write:

Now, let’s build a small example. Using Xcode 6 (currently in beta), create a Single View Application and name the project Singleton. Choose Swift as the programming language and save the project wherever you like. Then, add a new class to the project. Choose iOS -> Source -> Cocoa Touch Class. Name the class Monitor and make it a subclass of NSObject. Choose Swift as the language and save the class.

Next, open the Monitor.swift file and modify it as I previously described:

Then, open the ViewController.swift file and in the -viewDidLoad method create two constants of type Monitor and check that they are identical:

Afterward, run the app and look at the result in the LLDB console. There, you should see that the two objects are identical. Also, if you put a break point in correspondence of the if statement, you will get something similar to the following picture.

Clearly, the two constants monitor1 and monitor hold the same memory address.


Ultimately, this is simply one way of creating a singleton in Swift. Using computed properties is another possibility, but I’ll leave that investigation up to you.

Keep coding (in Swift),




(Visited 248 times, 1 visits today)