Sunday, January 9, 2022

Juri Pakaste: 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)
        }
    }
}


from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...