Why should we use the struct and class function in a singleton pattern?

I am just reading the code from the Udacity training material. The teacher makes an instance variable sharedInstancec struct, which is wrapped inclass function

Why can't we just do it static var?

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

        struct Singleton {
            static var sharedInstance = BugFactory()
        }      

        return Singleton.sharedInstance
    }
}

Why this is not recommended:

class BugFactory() {
    static var sharedInstance = BugFactory()
}
+4
source share
2 answers

In fact, it is recommended that you use your second code due to improvements in swift versions. Another thing you should consider is to declare your singleton object with static let, and also make the initializer private

class Bar{

    private init(){
        // initialization
    }

    static let shared = Bar()

}
+3
source

In fact, you should use static let to create sharedInstance / singleton.

, init(), , singleton.

, , Swift. , .

0

Source: https://habr.com/ru/post/1683150/


All Articles