Swift 单例

来源:互联网 发布:六级仔细阅读技巧知乎 编辑:程序博客网 时间:2024/06/05 07:12

第一种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 = 0            static var instance : Singleton? = nil        }        dispatch_once(&Static.onceToken) {            Static.instance = Singleton()        }        return Static.instance!    }}


0 0