Skip to main content

How to convert an AsyncSequence into a Sequence

About 2 minSwiftArticle(s)bloghackingwithswift.comcrashcourseswiftxcodeappstore

How to convert an AsyncSequence into a Sequence 관련

Swift Concurrency by Example

Back to Home

How to convert an AsyncSequence into a Sequence | Swift Concurrency by Example

How to convert an AsyncSequence into a Sequence

Updated for Xcode 15

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.

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:

extension AsyncSequence {
    func collect() async rethrows -> [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:

extension AsyncSequence {
    func collect() async rethrows -> [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)
    }
}

Download this as an Xcode projectopen in new window

Tips

Because we’ve made collect() use rethrows, you only need to call it using try if the call to reduce() would normally throw, so if you have an async sequence that doesn’t throw errors you can skip try entirely.

Similar solutions…
What’s the difference between Sequence, AsyncSequence, and AsyncStream? | Swift Concurrency by Example

What’s the difference between Sequence, AsyncSequence, and AsyncStream?
How to manipulate an AsyncSequence using map(), filter(), and more | Swift Concurrency by Example

How to manipulate an AsyncSequence using map(), filter(), and more
How to loop over an AsyncSequence using for await | Swift Concurrency by Example

How to loop over an AsyncSequence using for await
How to use continuations to convert completion handlers into async functions | Swift Concurrency by Example

How to use continuations to convert completion handlers into async functions

이찬희 (MarkiiimarK)
Never Stop Learning.