Skip to content

Instantly share code, notes, and snippets.

@daehn
Last active June 29, 2017 16:28
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 daehn/8ae8d2911c6f17580756c62af17e414b to your computer and use it in GitHub Desktop.
Save daehn/8ae8d2911c6f17580756c62af17e414b to your computer and use it in GitHub Desktop.
extension DispatchQueue {
/// Helper method to use when reading from a resource
/// that is being isolated by this queue.
///
/// Using this method retriving a value like this:
/// ```
/// var result: T?
/// queue.sync {
/// result = resource["key"]
/// }
/// ```
/// Can instead be done like this:
/// ```
/// let value = queue.access {
/// resource["key"]
/// }
/// ```
/// - parameter access: A closure to be synchronously dispatched onto the queue.
/// - returns: Forwards the return value of the passed in `access` closure.
@discardableResult func access<T>(_ access: @escaping () throws -> T) rethrows -> T {
var result: T? = nil
try sync { result = try access() }
return result!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment