Skip to content

Instantly share code, notes, and snippets.

@duemunk
Last active February 15, 2017 02:28
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duemunk/76a6294c598bf9a77cef to your computer and use it in GitHub Desktop.
Save duemunk/76a6294c598bf9a77cef to your computer and use it in GitHub Desktop.
An example of how you can use the error handling in Swift 2.0 for an asynchronous API.
typealias EmptyResult = () throws -> ()
typealias AsyncResult = (EmptyResult) -> ()
typealias JsonResult = () throws -> JSON
typealias AsyncJsonResult = (JsonResult) -> ()
class GetResponse {
func main() {
Response.updateAsync { result in
do {
// Call the result to let it try to throw an error
try result()
} catch {
print(error)
}
}
Response.getAsyncResult { jsonResult in
do {
// Call the result to let it try to throw an error
let json = try jsonResult()
// Use `json` as usual
} catch {
print(error)
}
}
}
}
class Response {
// Asynchronous empty response
class func updateAsync(result: AsyncJsonResult) {
Async.background { error in
if let error = error {
// Create result block that throws an error
result { throw error }
return
}
// Create result block that doesn't throw anything
result {}
}
}
// Asynchronous JSON response
class func getAsyncResult(result: AsyncJsonResult) {
Async.background { json, error in
if let error = error {
// Create result block that throws an error
result { throw error }
return
}
// Create result block that return the json
result { json }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment