swift - Swift 5.5:逐行异步迭代文件
问题描述
在WWDC2021 28:00 的“Platforms State of the Union”视频中提到,
[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
,但在文档中它说:
与其创建异步读取文件,不如
FileHandle
使用 file:// URL 与URLSession
. 其中包括传递异步字节序列的bytes(for:delegate:)
和bytes(from:delegate:)
方法,data(for:delegate:)
并data(from:delegate:)
立即返回文件的全部内容。
推荐阅读
- php - 将数据库中的字符串句子放入 TextField 值中
- azure - Azure 使用什么域类型?
- typescript - 如何触发
如果孩子使用 vue.js 调用 Axios 请求 - wordpress - Woocommerce 购物车中的多个外部 URL 产品结帐
- c# - Microsoft.Graph.ServiceException:代码:methodNotAllowed
- java - 如何将@ConfigurationProperties 与记录一起使用?
- python - 使用烧瓶在 html 中上传图片并在 doc 中放置图片时出现错误请求
- php - 刷新PHP后将变量保留在类中
- php - 无法更新 laravel 模型可见属性
- javascript - 为什么我有这个错误“StartTag:无效的元素名称”?