AsyncParsableCommand
A type that can be executed asynchronously, as part of a nested tree of commands.
- iOS
- 13+
- macOS
- 10.15+
- Mac Catalyst
- 13+
- tvOS
- 13+
- watchOS
- 6+
protocol AsyncParsableCommand : ParsableCommand
Browse conforming typesTo use async
/await
code in your commands’ run()
method implementations, follow these steps:
For the root command in your command-line tool, declare conformance to
AsyncParsableCommand
, whether or not that command uses asynchronous code.Apply the
@main
attribute to the root command. (Note: If your root command is in amain.swift
file, rename the file to the name of the command.)For any command that needs to use asynchronous code, declare conformance to
AsyncParsableCommand
and mark therun()
method asasync
. No changes are needed for subcommands that don’t use asynchronous code.
The following example declares a CountLines
command that uses Foundation’s asynchronous FileHandle.AsyncBytes
to read the lines from a file:
import Foundation
@main
struct CountLines: AsyncParsableCommand {
@Argument(transform: URL.init(fileURLWithPath:))
var inputFile: URL
mutating func run() async throws {
let fileHandle = try FileHandle(forReadingFrom: inputFile)
let lineCount = try await fileHandle.bytes.lines.reduce(into: 0)
{ count, _ in count += 1 }
print(lineCount)
}
}
Usage in Swift 5.5
In Swift 5.5, you need to declare a separate, standalone type as your asynchronous @main
entry point. Instead of designating your root command as @main
, as described above, use the code snippet below, replacing the placeholder with the name of your own root command. Otherwise, follow the steps above to use async
/await
code within your commands’ run()
methods.
@main struct AsyncMain: AsyncMainProtocol {
typealias Command = <#RootCommand#>
}
Implementing a Command’s Behavior
func run(
) async throws The behavior or functionality of this command.
Starting the Program
static func main(
) async Executes this command, or one of its subcommands, with the program’s command-line arguments.
protocol AsyncMainProtocol
A type that can designate an
AsyncParsableCommand
as the program’s entry point.