Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myobie/7fc8a7573b3c485dbffa3afb020da583 to your computer and use it in GitHub Desktop.
Save myobie/7fc8a7573b3c485dbffa3afb020da583 to your computer and use it in GitHub Desktop.
An example of swift async callbacks that either throw or return a result
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
// 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) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
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))
PlaygroundPage.current.finishExecution()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment