Created
January 16, 2024 05:41
-
-
Save josejuanqm/63a3cd81100c68f791028873c8067a6a to your computer and use it in GitHub Desktop.
Convert any closure to async easily with `withCheckedContinuation`
This file contains hidden or 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
| 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