Skip to main content

How to make async command-line tools and scripts

About 2 minSwiftArticle(s)bloghackingwithswift.comcrashcourseswiftxcodeappstore

How to make async command-line tools and scripts 관련

Swift Concurrency by Example

Back to Home

How to make async command-line tools and scripts | Swift Concurrency by Example

How to make async command-line tools and scripts

Updated for Xcode 15

If you’re writing a command-line tool, you can use async in conjunction with the @main attribute to launch your app into an async context immediately. To do this, first create the static main() method as you normally would with @main, then add async to it. You can optionally also add throws if you don’t intend to handle errors there.

For example, we could write a small command-line tool that fetches data from a URL and prints it out:

@main
struct UserFetcher {
    static func main() async throws {
        let url = URL(string: "https://hws.dev/users.csv")!

        for try await line in url.lines {
            print("Received user: \(line)")
        }
    }
}

Download this as an Xcode projectopen in new window

Tips

Just like using the @main attribute with a synchronous main() method, you should not include a main.swift file in your command-line project.

Using async and @main together benefits from the full range of Swift concurrency features. Behind the scenes, Swift will automatically create a new task in which it runs your main() method, then terminate the program when that task finishes.

Although it doesn’t work in the current Xcode release, the goal is for Swift to support async calls in top-level code. This would mean you could use main.swift files and remove most of the code in the previous sample – you could just go ahead and make async calls outside of a function.

Similar solutions…
How to call an async function using async let | Swift Concurrency by Example

How to call an async function using async let
What’s the difference between async let, tasks, and task groups? | Swift Concurrency by Example

What’s the difference between async let, tasks, and task groups?
Why can’t we call async functions using async var? | Swift Concurrency by Example

Why can’t we call async functions using async var?
How to use continuations to convert completion handlers into async functions | Swift Concurrency by Example

How to use continuations to convert completion handlers into async functions
How to create and use async properties | Swift Concurrency by Example

How to create and use async properties

이찬희 (MarkiiimarK)
Never Stop Learning.