Mobile Development

Singleton

A singleton is the same instance of a class for all that request it. Use a singleton to maintain a single point of control for your object.

A typical class permits callers to create as many instances of the class as they want, whereas with a singleton class, there can be only one instance of the class per process. [1]

An example

class ExampleSingleton {

    private var counter = 0

    class var sharedInstance : ExampleSingleton {
        struct Static {
            static let instance : ExampleSingleton = ExampleSingleton()
        }
        return Static.instance
    }

    func incrementCounter() -> Int {
        counter++
        return counter
    }
}

ExampleSingleton.sharedInstance.incrementCounter() // 1
ExampleSingleton.sharedInstance.incrementCounter() // 2
ExampleSingleton.sharedInstance.incrementCounter() // 3
ExampleSingleton.sharedInstance.incrementCounter() // 4

References

[1] Core Competency - Singleton - https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/Singleton.html

[2] Swift Singleton - GitHub - https://github.com/hpique/SwiftSingleton https://github.com/hpique/SwiftSingleton