Skip to content

Instantly share code, notes, and snippets.

@groue
Created July 12, 2015 14:16
Show Gist options
  • Save groue/f2ecc98b8301ed63d843 to your computer and use it in GitHub Desktop.
Save groue/f2ecc98b8301ed63d843 to your computer and use it in GitHub Desktop.
A function declared as rethrows that synchronously executes a throwing block in a dispatch_queue.
import Foundation
// A function declared as rethrows that synchronously executes a throwing
// block in a dispatch_queue.
//
// Based on Ransak's answer to https://forums.developer.apple.com/message/19685
func perform_sync(queue: dispatch_queue_t, block: () throws -> Void) rethrows {
func impl(queue: dispatch_queue_t, block: () throws -> Void, block2:((ErrorType) throws -> ()) ) rethrows {
var blockError: ErrorType? = nil
dispatch_sync(queue) {
do {
try block()
} catch {
blockError = error
}
}
if let blockError = blockError {
try block2(blockError)
}
}
try impl(queue, block: block, block2: { throw $0 })
}
// Some queue:
let queue = dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.rawValue), 0)
// try required for throwing closure:
do {
try perform_sync(queue) {
throw NSError(domain: "foo", code: 0, userInfo: nil)
}
} catch {
print("caught \(error)")
}
// try not required for non-throwing closure:
perform_sync(queue) {
print("hello")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment