Singletons in Swift

Johan Attali bio photo By Johan Attali

I've seen a lot of ways of creating singletons in swift. Most of them rely on creating static instances and opening up a public method sharedInstance().

Even the excellent @lilbitesofcocoa has a simple and very swiftly example.

But in all those cases they do not create real singletons in the sense that you could write more than one intentionally or by mistake. The ideal way of making them unique as they owe to be is first make the class final and most importantly make the init method private.

Ideally this would look like:

private let _singleton = Singleton()

final class Singleton {

    /// make initializer private
    private init() { }

    // make instance accessor a class variable
    class var sharedInstance: Singleton {
        return _singleton
    }
}

Making the initalizer private will prevent future instances from happening outside of that Singleton class file.