简体   繁体   中英

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

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()
}

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()

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM