在 "Platforms State of the Union" video of WWDC2021 28:00 有人提到
[Apple] even added support for asynchronously iterating line-by-line through a file
在 macOS 12/iOS 15 和 Swift 5.5 的基础中。
那个新 API 是什么,我现在如何通过文件异步逐行迭代?
最佳答案
他们添加的主要内容是 AsyncSequence
. AsyncSequence
就像 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
,但在 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 inURLSession
. These include thebytes(for:delegate:)
andbytes(from:delegate:)
methods that deliver an asynchronous sequence of bytes, anddata(for:delegate:)
anddata(from:delegate:)
to return the file’s entire contents at once.
关于 swift 5.5 : Asynchronously iterating line-by-line through a file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67920038/