0

The commonly accepted Singleton pattern for Swift uses a Struct inside a class variable/type property.

Instead of:

class MySingleton {
  class var sharedInstance: MySingleton {
    struct Singleton {
      static let instance = MySingleton()
    }
    return Singleton.instance
  }
}

Why do we not just do:

class MySingleton {
  class var sharedInstance: MySingleton {
      let instance = MySingleton()
      return instance
  }
}

Apologies if this is a very stupid question. But don't both leverage the thread-safety of constants and let?

Community
  • 1
  • 1
Doug Smith
  • 29,668
  • 57
  • 204
  • 388

2 Answers2

2

with your implementation, the 'sharedInstance' is not a singleton cause each time it gets called, it creates new instance of MySingleton. And, to create a static variable, you have to put it in struct o enums, otherwise, you will get compiler error

Duyen-Hoa
  • 15,384
  • 5
  • 35
  • 44
1

from Swift 1.2 & up you should use - see Apple's ref doc here :

class DeathStarSuperlaser {
    static let sharedInstance = DeathStarSuperlaser()

    private init() {
        // Private initialization to ensure just one instance is created.
    }
}
Ronny Webers
  • 5,244
  • 4
  • 28
  • 24