Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Swift Singleton #64

Open
v5tech opened this issue Jan 16, 2015 · 1 comment
Open

Swift Singleton #64

v5tech opened this issue Jan 16, 2015 · 1 comment
Labels

Comments

@v5tech
Copy link
Owner

v5tech commented Jan 16, 2015

http://www.synappse.pl/swift-first-steps-singleton/

//
//  Singleton.swift
//  Test
//
//  Created by Sebastian Suchanowski on 6/5/14.
//  Copyright (c) 2014 Synappse. All rights reserved.
//

import Foundation

class Singleton {

    class func sharedInstance() -> Singleton! {
        struct Static {
            static var instance: Singleton? = nil
            static var onceToken: dispatch_once_t = 0
        }

        dispatch_once(&Static.onceToken) {
            Static.instance = self()
        }

        return Static.instance!
    }

    @required init() {

    }

}
@v5tech
Copy link
Owner Author

v5tech commented Jan 16, 2015

//
//  TestTests.swift
//  TestTests
//
//  Created by Sebastian Suchanowski on 6/5/14.
//  Copyright (c) 2014 Synappse. All rights reserved.
//

import XCTest

class TestTests: XCTestCase {

    override func setUp() {
        super.setUp()
    }

    override func tearDown() {
        super.tearDown()
    }

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

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

    // Tests
    func testSingletonSharedInstanceCreated() {
        XCTAssertNotNil(getSharedInstance())
    }

    func testSingletonUniqueInstanceCreated() {
        XCTAssertNotNil(createUniqueInstance())
    }

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

}

@v5tech v5tech added Tips Swift and removed Tips labels Jan 16, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant