gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:57:16 30 4
gpt4 key购买 nike

"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 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.

关于 swift 5.5 : Asynchronously iterating line-by-line through a file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67920038/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com