Created
June 27, 2015 00:25
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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