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?
Just declare your initializer as private:
private init() {}
Now new instances can only be created from within the same file.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With