Last active
February 15, 2017 02:28
-
-
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.
This file contains 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
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