<!--
{
  "availability" : [
    "iOS: 13.0.0 -",
    "iPadOS: 13.0.0 -",
    "macCatalyst: 13.0.0 -",
    "macOS: 10.15.0 -",
    "tvOS: 13.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 6.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Swift",
  "identifier" : "/documentation/Swift/AsyncSequence/prefix(while:)-6yp5n",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Swift"
    ],
    "preciseIdentifier" : "s:Sci12_ConcurrencyE6prefix5whileAA32AsyncThrowingPrefixWhileSequenceVyxGSb7ElementQzYaKc_tKF"
  },
  "title" : "prefix(while:)"
}
-->

# prefix(while:)

Returns an asynchronous sequence, containing the initial, consecutive
elements of the base sequence that satisfy the given error-throwing
predicate.

```
@preconcurrency func prefix(while predicate: @escaping @Sendable (Self.Element) async throws -> Bool) rethrows -> AsyncThrowingPrefixWhileSequence<Self>
```

## Parameters

`predicate`

A 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 modified 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

Use `prefix(while:)` to produce values while elements from the base
sequence meet a condition you specify. The modified sequence ends when
the predicate closure returns `false` or throws an error.

In this example, an asynchronous sequence called `Counter` produces `Int`
values from `1` to `10`. The `prefix(_:)` method causes the modified
sequence to pass through values less than `8`, but throws an
error when it receives a value that’s divisible by `5`:

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

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)