FREE TRIAL: Accelerate your app development career with Hacking with Swift+! >>

How to convert an AsyncSequence into a Sequence

Paul Hudson    @twostraws   

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:

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()
}

Tip: 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.

Hacking with Swift is sponsored by Essential Developer

SPONSORED From August 2nd to 8th you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!

Save your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.