NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

What’s the difference between Sequence, AsyncSequence, and AsyncStream?

Paul Hudson    @twostraws   

Updated for Xcode 14.2

Swift provides several ways of receiving a potentially endless flow of data, allowing us to read values one by one, or loop over them using for, while, or similar.

The simplest is the Sequence protocol, which continually returns values until the sequence is terminated by returning nil. Lots of things conform to Sequence, including arrays, strings, ranges, Data, and more. Through protocol extensions Sequence also gives us access to a variety of methods, including contains(), filter(), map(), and others.

The AsyncSequence protocol is almost identical to Sequence, with the important exception that each element in the sequence is returned asynchronously. I realize that sounds obvious, but it actually has two major impacts on the way they work.

First, reading a value from the async sequence must use await so the sequence can suspend itself while reading its next value. This might be performing some complex work, for example, or perhaps fetching data from a server.

Second, more advanced async sequences known as async streams might generate values faster than you can read them, in which case you can either discard the extra values or buffer them to be read later on.

So, in the first case think of it like your code wanting values faster than the async sequence can make them, whereas in the second case it’s more like the async sequence generating data faster than than your code can read them.

Otherwise, Sequence and AsyncSequence have lots in common: the code to create a custom one yourself is almost the same, both can throw errors if you want, both get access to common functionality such as map(), filter(), contains(), and reduce(), and you can also use break or continue to exit loops over either of them.

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

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

Similar solutions…

Buy Pro Swift Buy Pro SwiftUI 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 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 Beyond Code

Was this page useful? Let us know!

Average rating: 3.0/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.