tl; dr: 如果使用的是Swift 1.2或更高版本,请使用 类常量 方法;如果需要支持早期版本,请使用 嵌套的struct 方法。
根据我在Swift中的经验,有三种方法可以实现支持延迟初始化和线程安全的Singleton模式。
类常数
class Singleton { static let sharedInstance = Singleton()}这种方法支持延迟初始化,因为Swift会延迟地初始化类常量(和变量),并且通过的定义是线程安全的
let。现在,这是实例化单例的官方推荐方法。
在Swift 1.2中引入了类常量。如果您需要支持Swift的早期版本,请使用下面的嵌套struct方法或全局常量。
嵌套结构
class Singleton { class var sharedInstance: Singleton { struct Static { static let instance: Singleton = Singleton() } return Static.instance }}在这里,我们将嵌套结构的静态常量用作类常量。这是在Swift
1.1及更早版本中缺少静态类常量的解决方法,并且仍然可以在函数中缺少静态常量和变量的情况下使用。
一次派遣
传统的Objective-C方法已移植到Swift。我可以肯定地说,嵌套结构方法没有任何优势,但是我还是把它放在这里,因为我发现语法上的差异很有趣。
class Singleton { class var sharedInstance: Singleton { struct Static { static var onceToken: dispatch_once_t = 0 static var instance: Singleton? = nil } dispatch_once(&Static.onceToken) { Static.instance = Singleton() } return Static.instance! }}请参阅此GitHub项目进行单元测试。



