Singletons in Swift

An iOS SDK Tutorial

iNVASIVECODE
[cocoa gurus]

--

In this post, I will to 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:

import Foundation
class Monitor : NSObject {

class func sharedMonitor() -> Monitor {
return _sharedMonitor
}

}
let _sharedMonitor: Monitor = { Monitor() }()

In the above source code, first, I imported the Foundation module to be able to subclass NSObject. Then, I created a class Monitor subclassing NSObject. The class contains a class function sharedMonitor. This function doesn’t take any input arguments and returns a class type Monitor. The _sharedMonitor variable is defined as a global variable and I initialized it to a closure that simply instantiated the Monitor class.

But, how can you use it? Well, suppose you need to reference this singleton from another object. You can write:

let monitor = Monitor.sharedMonitor()

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:

import Foundation

class Monitor: NSObject {

class func sharedMonitor() -> Monitor {
return _sharedMonitor
}

}
let _sharedMonitor : Monitor = { Monitor() }()

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

let monitor1 = Monitor.sharedMonitor()
let monitor2 = Monitor.sharedMonitor()

if monitor1 === monitor2 {
println("The two objects are identical")
} else {
println("The two objects are not 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.

Conclusion:

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),

Geppy

--

--

iNVASIVECODE
[cocoa gurus]

iOS consulting and training. Expertise include: machine vision, pattern-recognition, biometrics, and loT.