ylliX - Online Advertising Network

Quick tip: dispatch_once using Swift

There is no advantages of using this in Swift, but in case you have Objective-C you can do it using:

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!
    }
}

 

Leave a Reply