Swift 5.5:逐行异步迭代文件

Swift 5.5: Asynchronously iterating line-by-line through a file

在 28:00 的 "Platforms State of the Union" video of WWDC2021 中提到

[Apple] even added support for asynchronously iterating line-by-line through a file

in Foundation for macOS 12/iOS 15 和 Swift 5.5.

这是什么新内容 API,我现在如何异步地逐行迭代文件?

他们添加的主要内容是 AsyncSequenceAsyncSequence 类似于 Sequence,但它的 Iterator.next 方法是 async throws.

具体来说,您可以使用 URLSession.AsyncBytes.lines 获取文件中的 AsyncSequence 行。

假设你在一个async throws方法中,你可以这样做:

let (bytes, response) = try await URLSession.shared.bytes(from: URL(string: "file://...")!)
for try await line in bytes.lines {
    // do something...
}

请注意还有 FileHandle.AsyncBytes.lines, but in the documentation 它说:

Rather than creating a FileHandle to read a file asynchronously, you can instead use a file:// URL in combination with the async-await methods in URLSession. These include the bytes(for:delegate:) and bytes(from:delegate:) methods that deliver an asynchronous sequence of bytes, and data(for:delegate:) and data(from:delegate:) to return the file’s entire contents at once.