5

The first time I learned how to Implement Singleton Pattern in Swift is in this Book Pro Design Patterns in Swift.

The way I started implementing the Singleton Pattern is in the example below:

class Singleton {

    class var sharedInstance: Singleton {
        struct Wrapper {
            static let singleton = Singleton()
        }
        return Wrapper.singleton
    }

    private init() {
    }

}

But then I found this implementation while reading about Cocoa Design Patterns

class Singleton {

    static let sharedInstance = Singleton()

    private init() { 
    }

}

So my question is, what's the difference between the two implementations ?

Salim Braksa
  • 130
  • 10
  • 6
    You'll find it all in http://stackoverflow.com/questions/24024549/using-a-dispatch-once-singleton-model-in-swift. To make it short: The second implementation is the currently recommended one. The first implementation stems from Swift <= 1.1, where static class properties were not yet supported. – Martin R Feb 20 '16 at 17:13

1 Answers1

4

Back in Swift 1 days, static let wasn't implemented yet. The workaround was to create a wrapper struct. With Swift 2, this is not needed anymore.

Rudolf Adamkovič
  • 31,030
  • 13
  • 103
  • 118