Skip to content

Instantly share code, notes, and snippets.

@jacobsapps
Created April 30, 2025 21:31
Show Gist options
  • Save jacobsapps/f37a613de8e784fbe7351c036aaf9720 to your computer and use it in GitHub Desktop.
Save jacobsapps/f37a613de8e784fbe7351c036aaf9720 to your computer and use it in GitHub Desktop.
import Dispatch
extension Task {
static func sync(_ code: sending () async throws(Failure) -> Success) throws(Failure) -> Success {
let semaphore = DispatchSemaphore(value: 0)
nonisolated(unsafe) var result: Result<Success, Failure>? = nil
withoutActuallyEscaping(code) {
nonisolated(unsafe) let sendableCode = $0
let coreTask = Task<Void, Never>.detached(priority: .userInitiated) { @Sendable () async -> Void in
do {
result = .success(try await sendableCode())
} catch {
result = .failure(error as! Failure)
}
}
Task<Void, Never>.detached(priority: .userInitiated) {
await coreTask.value
semaphore.signal()
}
semaphore.wait()
}
return try result!.get()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment