1

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 ?

G.Abhisek
  • 1,034
  • 11
  • 44
  • Have a look at http://stackoverflow.com/questions/24024549/using-a-dispatch-once-singleton-model-in-swift, which 1) shows a simpler method, and 2) explains how it works (the `static let instance` property is assigned only once). – Martin R Aug 16 '16 at 09:53
  • But anyways the code gets running all the time we call the property. Isn't it ? So does that hamper? – G.Abhisek Aug 16 '16 at 09:56
  • Yes, but `return Static.instance` returns the *same instance* on each call. That mechanism was necessary in early versions of Swift, where static *class* properties were not supported. But you should find all that in the referenced Q&A. – Martin R Aug 16 '16 at 09:57
  • Okay then then as per my question, the computed property does not get allocated in the memory but the static property gets allocated in the memory once and for all. – G.Abhisek Aug 16 '16 at 10:05

0 Answers0