Swift question: there is a library that has some functionality, but it's implemented as an actor. I'm working a a completely synchronous program (a CLI app that builds a static website), but I want to use a function from this actor from normal non-concurrent code.

In the example code for using the library it awaits a function call. Is it possible to call this using some kind of concurrent-in-non-concurrent wrapper?

The library in question is MarkdownSyntax, and I suppose it's implemented as an actor for performance reasons in a UI context (do stuff in the background I presume?).

#swiftlang #askfedi

@torb You can always call into asynchronous code from synchronous code by using a semaphore from GCD to block while in the async call.
Like this:
```
func fetchSync() -> String {
let semaphore = DispatchSemaphore(value: 0)
var result = ""

Task {
let (data, _) = try await URLSession.shared.data(from: URL(string: "…")!)
result = String(data: data, encoding: .utf8) ?? ""
semaphore.signal()
}

semaphore.wait()
return result
}
```

@mortenbekditlevsen This is very close to what I ended up doing, inspired by both by comments of @V_, @Cyberbeni and this post on the Swift Forums: https://forums.swift.org/t/using-async-functions-from-synchronous-functions-and-breaking-all-the-rules/59782/4 ).

I ended up just making a version specific for my needs instead of making a generic one (among other things: my program always exits immediately upon any error so catching throws is not needed).

And it seems to work well!

Thanks for the help everyone!

Using `async` functions from synchronous functions (and breaking all the rules)

You can use a class to box the returned value. Something like this works (with all the safety caveats mentioned): fileprivate class Box<ResultType> { var result: Result<ResultType, Error>? = nil } /// Unsafely awaits an async function from a synchronous context. @available(*, deprecated, message: "Migrate to structured concurrency") func _unsafeWait<ResultType>(_ f: @escaping () async throws -> ResultType) throws -> ResultType { let box = Box<ResultType>() let sema = DispatchSemaphore(value...

Swift Forums