Swift 1.2 单例实现
第一种:类常量
class Singleton: NSObject { // 类常量 static let sharedInstance = Singleton() private override init() { super.init() } }
第二种:嵌套结构体
class Singleton: NSObject { // 嵌套结构体 class var sharedInstance: Singleton{ struct Static { static let instance: Singleton = Singleton() } return Static.instance } private override init() { super.init() } }
第三种:GCD:dispatch_once
class Singleton: NSObject { // GCD:dispatch_once class var sharedInstance:Singleton { struct Static { static var onceToken:dispatch_once_t = 0 static var instance:Singleton? = nil } dispatch_once(&Static.onceToken,{ () -> Void in Static.instance = Singleton() }) return Static.instance! } private override init() { super.init() } }
参考:http://stackoverflow.com/questions/24024549/dispatch-once-singleton-model-in-swift
原文链接:https://www.f2er.com/swift/325960.html