11import Foundation
22
3- #if swift(<6.0)
43/// A type-erasing wrapper for any `AsyncSequence`.
54@available ( * , deprecated, message: " This type is deprecated and will be removed in a future version " )
65public struct AnyAsyncSequence < Element> : AsyncSequence {
76
87 private var _makeAsyncIterator : ( ) -> AsyncIterator
9-
8+
109 /// Initializes a new instance with the provided iterator-making closure.
1110 /// - Parameter makeAsyncIterator: A closure that returns an `AsyncIterator`.
1211 public init ( makeAsyncIterator: @escaping ( ) -> AsyncIterator ) {
1312 _makeAsyncIterator = makeAsyncIterator
1413 }
15-
14+
1615 /// Initializes a new instance by wrapping an existing `AsyncSequence`.
1716 /// - Parameter sequence: An `AsyncSequence` whose elements to iterate over.
1817 public init < S: AsyncSequence > ( _ sequence: S ) where S. Element == Element {
1918 self . init {
20- var iterator = sequence. makeAsyncIterator ( )
19+ let box = Box ( sequence. makeAsyncIterator ( ) )
2120 return AsyncIterator {
22- try await iterator. next ( )
21+ try await box . iterator. next ( )
2322 }
2423 }
2524 }
@@ -28,29 +27,36 @@ public struct AnyAsyncSequence<Element>: AsyncSequence {
2827 public func makeAsyncIterator( ) -> AsyncIterator {
2928 _makeAsyncIterator ( )
3029 }
31-
30+
3231 /// The iterator for `AnyAsyncSequence`.
3332 public struct AsyncIterator : AsyncIteratorProtocol {
34-
33+
3534 private var _next : ( ) async throws -> Element ?
36-
35+
3736 public init ( next: @escaping @Sendable ( ) async throws -> Element ? ) {
3837 _next = next
3938 }
40-
39+
4140 public mutating func next( ) async throws -> Element ? {
4241 try await _next ( )
4342 }
4443 }
44+
45+ private final class Box < I: AsyncIteratorProtocol > where I. Element == Element {
46+ var iterator : I
47+ init ( _ iterator: I ) {
48+ self . iterator = iterator
49+ }
50+ }
4551}
4652
4753public extension AsyncSequence {
4854
4955 /// Erases the type of this sequence and returns an `AnyAsyncSequence` instance.
5056 /// - Returns: An instance of `AnyAsyncSequence` wrapping the original sequence.
5157 @available ( * , deprecated, message: " This method is deprecated and will be removed in a future version " )
58+ @_disfavoredOverload
5259 func eraseToAnyAsyncSequence( ) -> AnyAsyncSequence < Element > {
5360 AnyAsyncSequence ( self )
5461 }
5562}
56- #endif
0 commit comments