为什么建议的Swift单例实现使用结构?
Swift普遍接受的Singleton模式在类变量/类型属性中使用Struct。
代替:
class MySingleton { class var sharedInstance: MySingleton { struct Singleton { static let instance = MySingleton() } return Singleton.instance } }
为什么我们不这样做:
class MySingleton { class var sharedInstance: MySingleton { let instance = MySingleton() return instance } }
如果这是一个非常愚蠢的问题,请道歉。 但是,不要既利用常量的线程安全又let
?
对于你的实现,’sharedInstance’不是单独的原因,每次调用它时,它都会创建MySingleton的新实例。 并且,要创建静态变量,必须将其放在struct o enums中,否则,您将收到编译器错误
从Swift 1.2及以上你应该使用 – 请参阅Apple的ref doc:
class DeathStarSuperlaser { static let sharedInstance = DeathStarSuperlaser() private init() { // Private initialization to ensure just one instance is created. } }