Skip to content

Instantly share code, notes, and snippets.

@eleev
Last active March 30, 2018 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eleev/8abcba47320a0d5b3183465180743572 to your computer and use it in GitHub Desktop.
Save eleev/8abcba47320a0d5b3183465180743572 to your computer and use it in GitHub Desktop.
DispatchOnce + Swift 3 (and above).swift
public extension DispatchQueue {
// MARK: - Properties
private static var _onceTracker = [String]()
// MARK: - Methods
/// Executes a block of code, associated with a unique token, only once. The code is thread safe and will onle execute the code once even in the presence of multithreaded calls.
///
/// - Parameters:
/// - token: is a unique reverse DNS-style name such as io.eleev.astemir or a GUID
/// - block: is a non-escaping closure that is executed only once
public class func once(token: String, block: ()->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