Swift 1.2 实现单例

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

    原文作者:laznrbfe
    原文地址: https://segmentfault.com/a/1190000003746446
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞