WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

How to make async command-line tools and scripts

Paul Hudson    @twostraws   

Updated for Xcode 14.2

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 project

Tip: 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.

Save 50% in my WWDC23 sale.

SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.0/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.