SWIFT 5.5:在文件中逐行异步迭代

人气:289 发布:2022-10-16 标签: swift macos foundation wwdc swift5.5

问题描述

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

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

在适用于MacOS 12/iOS 15和SWIFT 5.5的Foundation中。

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

推荐答案

他们添加的主要功能是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中显示:

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

923