Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS8 + Swift: Create a true singleton class [duplicate]

Tags:

ios

swift

I'm creating a singleton class in Swift as follows:

class SingletonClass {

    class var sharedInstance: SingletonClass {
        struct Singleton {
            static let instance = SingletonClass()
        }

        return Singleton.instance
    }


    var a: Int?
    var b: Int?
    var c: Int?
}

This allows me to access a shared instance from anywhere:

SingletonClass.sharedInstance

While this works, it doesn't make this instance the only possible one in the entire system, which is what singletons are all about.
That means that I can still create a whole new instance such as this:

let DifferentInstance: SingletonClass = SingletonClass()

And the shared instance is not the only one anymore.

So my question is this: Is there a way in Swift to create a true singleton class, where only one instance is possible system-wide?

like image 532
Darkshore Grouper Avatar asked Dec 05 '22 05:12

Darkshore Grouper


2 Answers

Just declare your initializer as private:

private init() {}

Now new instances can only be created from within the same file.

like image 134
drewag Avatar answered Dec 25 '22 22:12

drewag


You have misunderstood the nature of singleton. The purpose of singleton is provide a singleton, not to prevent evil. I can make another UIApplication instead of the sharedApplication but that would be stupid since it would not be the sharedApplication. I can make another NSNotificationCenter instead of the defaultCenter but that would be stupid since it would not be the defaultCenter. The point is not to stop me from stupidity but to provide a factory singleton, and that is what you are already doing. Don't worry, be happy.

like image 45
matt Avatar answered Dec 25 '22 21:12

matt