3

I'm just reading a code from Udacity learning stuff. The teacher makes an instance variable sharedInstance with a struct that wrapped in a class function

Why can we not simply make a static var?

class BugFactory() {
    class func sharedInstance() -> BugFactory {      

        struct Singleton {
            static var sharedInstance = BugFactory()
        }      

        return Singleton.sharedInstance
    }
}

Why It's not recommended:

class BugFactory() {
    static var sharedInstance = BugFactory()
}
Roham Rafii
  • 2,929
  • 7
  • 35
  • 49
Vahid
  • 3,352
  • 2
  • 34
  • 42
  • 1
    Because in old, old historic Swift, classes could not have static vars. – OOPer Aug 07 '17 at 08:07
  • @OOPer, So, it means using `static var` for singleton pattern is OK now? – Vahid Aug 07 '17 at 08:10
  • you can have a look at [here](https://stackoverflow.com/questions/36788169/whats-the-difference-between-struct-based-and-class-based-singletons) about the difference between struct based and class based singleton. As mentioned above in the old historic Swift, classes couldn't have static vars hence you needed to use struct and wrap it inside a class. – sarosh mirza Aug 07 '17 at 08:11
  • I recommend using `static let` rather than `static var`, but yes it's the [recommended way by Apple](https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html#//apple_ref/doc/uid/TP40014216-CH7-ID177). – OOPer Aug 07 '17 at 08:13
  • According to the Xcode Release Notes, [static members of class are introduced in Swift 1.2/Xcode 6.3](https://developer.apple.com/library/content/releasenotes/DeveloperTools/RN-Xcode/Chapters/Introduction.html#//apple_ref/doc/uid/TP40001051-CH1-SW393). But as you see, there are some people who cannot refresh old knowledge. – OOPer Aug 07 '17 at 08:18

2 Answers2

5

Actually it is recommended to use your second code because of the improvements in the versions of swift.One more thing that you should consider is to declare your singleton object using static let and also make the initializer private

class Bar{

    private init(){
        // initialization
    }

    static let shared = Bar()

}
0

You should actually use static let to create sharedInstance/singleton.

Also make sure to have private init() method, so that any other class does not unintentionally creates another instance of the class which is supposed to singleton.

The tutorial you are referencing might be using some older Swift version. If you have comment options there on video make a comment.

Mohammad Sadiq
  • 5,070
  • 28
  • 29