问题描述
在"Platforms State of the Union" video of WWDC2021中提到28:00
[Apple]甚至添加了对在文件中逐行异步迭代的支持
在适用于MacOS 12/iOS 15和SWIFT 5.5的Foundation中。
什么是新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中显示:
不是创建FileHandle
来异步读取文件,而是可以将file://URL与URLSession
中的async-aWait方法结合使用。其中包括提供异步字节序列的bytes(for:delegate:)
和bytes(from:delegate:)
方法,以及同时返回文件全部内容的data(for:delegate:)
和data(from:delegate:)
方法。