Why does the suggested Swift singleton implementation use a struct?

前端 未结 2 1389
臣服心动
臣服心动 2021-01-16 18:32

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

Instead of:

class MySingleton {
  class var s         


        
2条回答
  •  野的像风
    2021-01-16 19:22

    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.
        }
    }
    

提交回复
热议问题