SWIFT 5.5:在文件中逐行异步迭代 [英] Swift 5.5: Asynchronously iterating line-by-line through a file
本文介绍了SWIFT 5.5:在文件中逐行异步迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在"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:)
方法。
这篇关于SWIFT 5.5:在文件中逐行异步迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文