2025-02-08 16:30:07
,某些文章具有时效性,若有错误或已失效,请在下方留言。If you’re writing a command-line tool with Swift, you can use async code in two ways: if you’re using main.swift you can immediately make and use async
functions as normal, and if you aren’t using main.swift you can use the @main
attribute to launch your app into an async context immediately.
如果你正在使用 Swift 编写命令行工具,你可以通过两种方式使用异步代码:如果你使用的是 main.swift,你可以立即像往常一样制作和使用异步
函数,如果你不使用 main.swift,你可以使用 @main
属性立即将你的应用程序启动到异步上下文中。
Either way, keep in mind that you should wait for your work to complete before allowing your program to terminate, otherwise it might not complete.
无论哪种方式,请记住,您应该等待工作完成,然后再允许程序终止,否则它可能无法完成。
Let’s try an example using both approaches. First, if you’re using main.swift, you can just start using await
and similar like this:
让我们尝试使用这两种方法的示例。首先,如果你正在使用 main.swift,你可以开始使用 await
和类似的方法,如下所示:
let url = URL(string: "https://hws.dev/users.csv")!
for try await line in url.lines {
print("Received user: \(line)")
}
If you aren’t using main.swift and instead prefer to use the @main
attribute, you should 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.
如果你没有使用 main.swift,而是更喜欢使用 @main
属性,你应该首先像通常使用 @main
一样创建静态 main()
方法,然后向其添加 async
。如果您不打算在那里处理错误,也可以选择添加 throws
。
So, here’s the previous example rewritten using @main
:
所以,下面是使用 @main
重写的上一个示例:
@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)")
}
}
}
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.
在后台,Swift 将自动创建一个新任务,在其中运行您的 main()
方法,然后在该任务完成时终止程序。
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.
提示: 就像将 @main
属性与同步 main()
方法一起使用一样,您不应在命令行项目中包含 main.swift 文件。