Async/await command line tool in Xcode 14.3
Update 10/4/2024: It appears in Xcode 15.3 nothing special is required and can use await right next to the hello world print.
TLDR: add @main
and rename main.swift
To create a command line tool in Xcode 14.3 that uses async/await there are a few tweaks required. When we create the project using the Command Line Tool template we are left with a main.swift
and the code below:
import Foundation
print("Hello, World!")
To use async/await we need to replace this with @main
as follows:
import Foundation
@main
struct AsyncCommandLine {
static func main() async throws {
try await Task.sleep(for:.seconds(1)) // just to test async/await
print("Hello, World!")
}
}
Now when we compile we get the error:
'main' attribute cannot be used in a module that contains top-level code
To fix this you can simply rename main.swift
to AsyncCommandLine.swift
I hope this helped!