首页 > 解决方案 > Swift 5.5:逐行异步迭代文件

问题描述

WWDC2021 28:00 的“Platforms State of the Union”视频中提到,

[Apple] 甚至增加了对逐行异步迭代文件的支持

在 macOS 12/iOS 15 和 Swift 5.5 的基础中。

什么是新 API,我现在如何通过文件异步逐行迭代?

标签: swiftmacosfoundationwwdcswift5.5

解决方案


他们添加的主要功能是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,但在文档中它说:

与其创建异步读取文件,不如FileHandle使用 file:// URL 与URLSession. 其中包括传递异步字节序列的bytes(for:delegate:)bytes(from:delegate:)方法,data(for:delegate:)data(from:delegate:)立即返回文件的全部内容。


推荐阅读