Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singletons In Swift

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 ?

like image 385
Salim Braksa Avatar asked Sep 26 '22 07:09

Salim Braksa


1 Answers

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.

like image 60
Rudolf Adamkovič Avatar answered Sep 28 '22 05:09

Rudolf Adamkovič