I create a single 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 the shared instance from anywhere:
SingletonClass.sharedInstance
While this works, it does not make this instance the only one possible in the whole system, and this is what singles are talking about.
This means that I can still create a completely new instance, for example:
let DifferentInstance: SingletonClass = SingletonClass()
And the shared instance is no longer the only one.
So my question is this: is there a way in Swift to create a real singleton class where only one instance is possible in a system-wide one?
source
share