当前位置: 代码迷 >> 综合 >> Swift 单例
  详细解决方案

Swift 单例

热度:29   发布时间:2023-12-15 01:56:41.0

第一种Global constant

let _SingletonSharedInstance = Singleton()
class Singleton  {class var sharedInstance : Singleton {return _SingletonSharedInstance}
}

第二种Nested struct

class Singleton {class var sharedInstance : Singleton {struct Static {static let instance : Singleton = Singleton()}return Static.instance}
}

第三种 dispatch_once

class Singleton {class var sharedInstance : Singleton {struct Static {static var onceToken : dispatch_once_t = 0static var instance : Singleton? = nil}dispatch_once(&Static.onceToken) {Static.instance = Singleton()}return Static.instance!}
}