在"Platforms State of the Union";WWDC2021在28:00的视频中提到
[Apple]甚至添加了对通过文件逐行异步迭代的支持
基于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
,但在文档中它说:
您可以将file://URL与
URLSession
中的异步等待方法结合使用,而不是创建FileHandle
来异步读取文件。其中包括传递异步字节序列的bytes(for:delegate:)
和bytes(from:delegate:)
方法,以及一次返回文件全部内容的data(for:delegate:)
和data(from:delegate:)
方法。