Here I was going through different ways of creating a singleton class. All along I found this git repo -https://github.com/hpique/SwiftSingleton
I found the following code sniper for creating singletons.
class SingletonB {
class var sharedInstance: SingletonB {
struct Static {
static let instance: SingletonB = SingletonB()
}
return Static.instance
}
}
Okay the class property sharedInstance
is a computed property. Computed property are not allocated any memory & the value of the property gets computed each and every time it gets called.
Question - If so is the case then it violates the principle of singletons that there shall be only 1 instance of the class through out the whole application and the instance is initialised only once. But here in case of computed property the value for sharedInstance
gets computed each and every time we call this property.
So how is this mechanism going behind the screens ?