How to convert an AsyncSequence into a Sequence 如何将 AsyncSequence 转换为 Sequence

How to convert an AsyncSequence into a Sequence 如何将 AsyncSequence 转换为 Sequence

温馨提示:本文最后更新于2025-02-08 10:30:23,某些文章具有时效性,若有错误或已失效,请在下方留言

Swift does not provide a built-in way of converting an AsyncSequence into a regular Sequence, but often you’ll want to make this conversion yourself so you don’t need to keep awaiting results to come back in the future.
Swift 没有提供将 AsyncSequence 转换为常规 Sequence 的内置方法,但您通常需要自己进行此转换,因此无需一直等待将来返回结果。

The easiest thing to do is call reduce(into:) on the sequence, appending each item to an array of the sequence’s element type. To make this more reusable, I’d recommend adding an extension such as this one:
最简单的方法是在序列上调用 reduce(into:),将每个项目附加到序列元素类型的数组中。为了使其更具可重用性,我建议添加如下扩展:

extension AsyncSequence {
    func collect() async throws -> [Element] {
        try await reduce(into: [Element]()) { $0.append($1) }
    }
}

With that in place, you can now call collect() on any async sequence in order to get a simple array of its values. Because this is an async operation, you must call it using await like so:
有了这个,你现在可以在任何异步序列上调用 collect() 来获取其值的简单数组。因为这是一个异步作,所以您必须使用 await 调用它,如下所示:

extension AsyncSequence {
    func collect() async throws -> [Element] {
        try await reduce(into: [Element]()) { $0.append($1) }
    }
}

func getNumberArray() async throws -> [Int] {
    let url = URL(string: "https://hws.dev/random-numbers.txt")!
    let numbers = url.lines.compactMap(Int.init)
    return try await numbers.collect()
}

if let numbers = try? await getNumberArray() {
    for number in numbers {
        print(number)
    }
}
how-to-convert-an-asyncsequence-into-a-sequence-1.zip
zip文件
50.4K

Tip: If you prefer, you can make collect() use rethrows rather than throws, so that you only need to call it using try if the call to reduce() would normally throw. This means if you have an async sequence that doesn’t throw errors, you can skip try entirely.
提示: 如果你愿意,你可以让 collect() 使用 rethrows 而不是 throws,这样你只需要在调用 reduce() 通常会抛出时使用 try 调用它。这意味着如果你有一个不会引发错误的 async 序列,你可以完全跳过 try

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享