I'm trying to reuse some async marked code that works great in a SwiftUI application in a simple Swift-Command line tool. Lets assume for simplicity that I'd like to reuse a function
func fetchData(base : String) async throws -> SomeDate
{
let request = createURLRequest(forBase: base)
let (data, response) = try await URLSession.shared.data(for: request)
guard (response as? HTTPURLResponse)?.statusCode == 200 else {
throw FetchError.urlResponse
}
let returnData = try! JSONDecoder().decode(SomeData.self, from: data)
return returnData
}
in my command line application. A call like
let allInfo = try clerk.fetchData("base")
in my "main-function" gives the error message 'async' call in a function that does not support concurrency.
What is the correct way to handle this case.
Thanks Patrick
To call an async method the call must take place inside an async method or wrapped in a Task.
Further the method must be called wirh await
Task {
do {
let allInfo = try await clerk.fetchData("base")
} catch {
print(error)
}
}
You can make the entry point of the CLI async with this syntax
@main
struct CLI {
static func main() async throws {
let args = CommandLine.arguments
...
}
The name of the struct is arbitrary.
You need to rename the file from main.swift to CLI.swift to fix the error 'main' attribute cannot be used in a module that contains top-level code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With