Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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