第一种, 类常量Class constant
,建议使用方式
class Singleton {
static let sharedInstance = Singleton()
}
第二种嵌套结构体变量格式
class Singleton {
class var sharedInstance: Singleton {
struct Static {
static let instance: Singleton = Singleton()
}
return Static.instance
}
}
第三种最不建议, 但最像Oc的创建方式dispatch_once
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!
}
}
原文链接 https://stackoverflow.com/questions/24024549/using-a-dispatch-once-singleton-model-in-swift/24147830#24147830