Swift first steps: Singleton

Next day next challenge, as simple as it may be – creating Singleton – it can bring some problems in now known language using not known syntax. Lucky enough I was able to write my first Swift class and make it a working singleton (I have wrote unit tests that will testify it). So let’s take a look and next explain.

import Foundation

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

First we are importing Foundation – we need that because GCD functions like dispatch_once are there – so it won’t work without it. Next we have to create static method ahhh.. function 😉 using class keyword and set the return type – how I came to that was going into UIApplication class and looking at the header file translated to Swift by Apple – there I have found same kind of declaration for sharedInstance.
What happens inside sharedInstance function is more or less the same what we did before in pure Objective-C, so what have left here is init() function which has to be required so we will be able to call self() inside the dispatch_once block.

Updated for Swift 2.X — it got a lot easier. We need to override init() and make it private and we are pretty much done.

import XCTest

class TestTests: XCTestCase {

    override func setUp() {

    override func tearDown() {

    // Helpers
    func createUniqueInstance() -> Singleton {
        return Singleton()

    func getSharedInstance() -> Singleton {
        return Singleton.sharedInstance

    // Tests
    func testSingletonSharedInstanceCreated() {

    func testSingletonUniqueInstanceCreated() {

    func testSingletonReturnsSameSharedInstances() {
        var s1 = getSharedInstance()
        var s2 = getSharedInstance()
        XCTAssertEqualObjects(s1, s2)

    func testSingletonSharedInstanceSameAsUniqueInstance() {
        var s1 = getSharedInstance()
        var s2 = createUniqueInstance()
        XCTAssertNotEqualObjects(s1, s2)

    func testSingletonReturnsSameUniqueInstances() {
        var s1 = createUniqueInstance()
        var s2 = createUniqueInstance()
        XCTAssertNotEqualObjects(s1, s2)


BTW. I did a little trick to make the test methods work – I’ve added a parent class to singleton, like this:

class Singleton: NSObject {

All green!

singleton unit tests

Using tests presented above I was able to check for sure that singleton works. If you don’t believe me then do it yourself 😉

Happy coding!

Comments ( 0 )

    Leave A Comment

    Your email address will not be published. Required fields are marked *