Swift 1.2 實現單例

laznrbfe發表於2015-09-14

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

相關文章