Contents

filter(_:)

Creates an asynchronous sequence that contains, in order, the elements of the base sequence that satisfy the given error-throwing predicate.

Declaration

@preconcurrency func filter(_ isIncluded: @escaping  @Sendable (Self.Element) async throws -> Bool) -> AsyncThrowingFilterSequence<Self>

Parameters

  • isIncluded:

    An error-throwing closure that takes an element of the asynchronous sequence as its argument and returns a Boolean value that indicates whether to include the element in the filtered sequence.

Return Value

An asynchronous sequence that contains, in order, the elements of the base sequence that satisfy the given predicate. If the predicate throws an error, the sequence contains only values produced prior to the error.

Discussion

In this example, an asynchronous sequence called Counter produces Int values from 1 to 10. The filter(_:) method returns true for even values and false for odd values, thereby filtering out the odd values, but also throws an error for values divisible by 5:

do {
    let stream = Counter(howHigh: 10)
        .filter {
            if $0 % 5 == 0 {
                throw MyError()
            }
            return $0 % 2 == 0
        }
    for try await number in stream {
        print(number, terminator: " ")
    }
} catch {
    print("Error: \(error)")
}
// Prints "2 4 Error: MyError() "

See Also

Excluding Elements