Async Swift and ArgumentParser
Swift 5.5 brought us async functions. ArgumentParser is the most popular way to write command line interfaces with Swift. Swift 5.5 supports an asynchronous main function, but ArgumentParser does not, as of version 1.0.2.
To bridge this gap, you can call ArgumentParser manually from your asynchronous main function, like this:
import ArgumentParser
struct MyCommand: ParsableCommand {
@Argument var arg: String
// Usually you'd write a `run` function, but it has to be synchronous.
func runAsync() async throws {
/* … */
}
}
@main
enum Main {
static func main() async throws {
let args = Array(CommandLine.arguments.dropFirst())
do {
let command = try MyCommand.parse(args)
try await command.runAsync()
} catch {
MyCommand.exit(withError: error)
}
}
}
9 January 2022