Primary Associated Types for AsyncSequences

Hi,

I hit a roadblock in some code that I wanted to write today, because AsyncSequence does not have a primary associated type, so returning something like some AsyncSequence<String> is not possible.

According to the relevant pitch this is a deliberate omission, because of ongoing discussion.

So, I wanted to politely ask: What the is state of those discussion?

3 Likes

Can't speak to the official introduction, but you have a workaround available by defining this protocol in your project today:

public protocol ATAsyncSequence<Element>: AsyncSequence { }

and extend whatever concrete sequence types you use to conform to ATAsyncSequence:

extension AsyncCompactMapSequence: ATAsyncSequence { }
extension AsyncFilterSequence: ATAsyncSequence { }
extension AsyncFlatMapSequence: ATAsyncSequence { }
...

Once you have that in your project you can use ATAsyncSequence wherever you needed the specificity:

func collectZeros(_ input: some ATAsyncSequence<Int>) -> some ATAsyncSequence<Int> {
    return input.filter { $0 == 0 }
}
4 Likes

That's pretty neat, thanks.

I also ended up using my own protocol that inherits from AsyncSequence, but then I created a generic type that wraps an AsyncSequence and conforms to what you call ATAsyncSequence. With a convenience extension on AsyncSequence the conversion is not toooo painful.

But I think I should consider your approach, because there is no wrapping, no convenience property and I don't think that custom implementations of AsyncSequence are that common for my use case.