Skip to content

Instantly share code, notes, and snippets.

@preble
Created June 27, 2015 00:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save preble/df59846e5229be286114 to your computer and use it in GitHub Desktop.
Save preble/df59846e5229be286114 to your computer and use it in GitHub Desktop.
An overload of dispatch_sync that throws any error thrown by the closure. (Swift 2)
import Foundation
/// Call a throwing block synchronously.
func dispatch_sync(queue: dispatch_queue_t, block: () throws -> ()) throws {
var error: ErrorType?
dispatch_sync(queue) {
do {
try block()
} catch let caughtError {
error = caughtError
}
}
if let error = error {
throw error
}
}
// Usage:
enum MyError: ErrorType {
case OhNo
}
let queue = dispatch_queue_create("test", nil)
do {
try dispatch_sync(queue) {
throw MyError.OhNo
}
} catch let e {
print("Caught! \(e)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment