Skip to content

Instantly share code, notes, and snippets.

@josejuanqm
Created January 16, 2024 05:41
Show Gist options
  • Select an option

  • Save josejuanqm/63a3cd81100c68f791028873c8067a6a to your computer and use it in GitHub Desktop.

Select an option

Save josejuanqm/63a3cd81100c68f791028873c8067a6a to your computer and use it in GitHub Desktop.
Convert any closure to async easily with `withCheckedContinuation`
func foo(_ completion: (Bool) -> Void) {
completion(Bool.random())
}
func bar() async -> Result<Bool, Never> {
return await withCheckedContinuation { continuation in
foo { result in
continuation.resume(returning: .success(result))
}
}
}
func baz() {
Task {
guard case let .success(result) = await bar() else {
return
}
// if the result is success, we unwrap the value and use it here
if result {
// All good!
} else {
// Oh no
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment