【问题标题】:Swift 5.5: Asynchronously iterating line-by-line through a fileSwift 5.5:逐行异步迭代文件
【发布时间】:2021-08-27 09:30:02
【问题描述】:

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

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

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

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

【问题讨论】:

标签: swift macos foundation wwdc swift5.5


【解决方案1】:

他们添加的主要内容是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,但在documentation 中写着:

您可以将 file:// URL 与 URLSession 中的 async-await 方法结合使用,而不是创建 FileHandle 来异步读取文件。其中包括传递异步字节序列的 bytes(for:delegate:)bytes(from:delegate:) 方法,以及一次返回文件的全部内容的 data(for:delegate:)data(from:delegate:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-13
    • 1970-01-01
    • 1970-01-01
    • 2011-01-18
    • 1970-01-01
    • 2017-11-15
    • 2014-02-04
    相关资源
    最近更新 更多