Skip to content

Instantly share code, notes, and snippets.

@myobie
Last active November 29, 2017 02:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myobie/e1842c329cd1c48c00029099a627ba33 to your computer and use it in GitHub Desktop.
Save myobie/e1842c329cd1c48c00029099a627ba33 to your computer and use it in GitHub Desktop.
An example of swift async callbacks that either throw or return a result
import Foundation
// either throws an Error or returns a String result
typealias ThrowsCallback = () throws -> (String)
enum AsyncError: Error {
case kaboom
}
func asyncActionWithCallback(_ someData: String, callback: @escaping (ThrowsCallback) -> Void) {
if someData == "please error" {
callback({ throw AsyncError.kaboom })
} else {
callback({ return "you provided \(someData)" })
}
}
asyncActionWithCallback("Hello") { result in
let value = try? result()
print(String(describing: value))
}
asyncActionWithCallback("please error") { result in
let value = try? result()
print(String(describing: value))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment