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

标签 swift macos foundation wwdc swift5.5

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

相关文章:

ios - NSLocaleCountryCode 返回 nil

ios - 'UIWindow' 没有可见的 @interface 声明选择器 'recursiveDescription'

objective-c - alloc + init 内存使用机制

ios - 如何从 swift 中的 didUpdateToLocation 方法获取旧位置值

macos - 将 NSTableView 绑定(bind)到 Swift 中的字符串数组

ios - Xcode - 构建应用程序 - 问题

macos - Swift 中的自定义 NSmenuitem

objective-c - 从 Cocoa 应用程序执行终端命令

swift - 为什么导航栏后退按钮项消失? swift 4

swift - 在任何情况下都需要调用 `disposed(by:)` 吗?