Skip to content

Instantly share code, notes, and snippets.

@alexj70
Last active April 28, 2017 10:59
Show Gist options
  • Save alexj70/7b1b1d23c920dddd5c8095fba0862c78 to your computer and use it in GitHub Desktop.
Save alexj70/7b1b1d23c920dddd5c8095fba0862c78 to your computer and use it in GitHub Desktop.
DispatchOne Swift 3

DispatchOnce

Swift3.0

public extension DispatchQueue {
    private static var _onceTracker = [String]()
    
    public class func once(file: String = #file, function: String = #function, line: Int = #line, block:(Void)->Void) {
        let token = file + ":" + function + ":" + String(line)
        once(token: token, block: block)
    }
    
    /**
     Executes a block of code, associated with a unique token, only once.  The code is thread safe and will
     only execute the code once even in the presence of multithreaded calls.
     
     - parameter token: A unique reverse DNS style name such as com.vectorform.<name> or a GUID
     - parameter block: Block to execute once
     */
    public class func once(token: String, block:(Void)->Void) {
        objc_sync_enter(self)
        defer { objc_sync_exit(self) }
        
        if _onceTracker.contains(token) {
            return
        }
        
        _onceTracker.append(token)
        block()
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment