---
title: "prefix(while:)"
framework: swift
role: symbol
role_heading: Instance Method
path: "swift/taskgroup/prefix(while:)"
---

# prefix(while:)

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

## Declaration

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

## Parameters

- `predicate`: A closure that takes an element as a parameter and returns a Boolean value indicating whether the element should be included in the modified sequence.

## Return Value

Return Value An asynchronous sequence of the initial, consecutive elements that satisfy predicate.

## Discussion

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. In this example, an asynchronous sequence called Counter produces Int values from 1 to 10. The prefix(while:) method causes the modified sequence to pass along values so long as they aren’t divisible by 2 and 3. Upon reaching 6, the sequence ends: let stream = Counter(howHigh: 10)     .prefix { $0 % 2 != 0 || $0 % 3 != 0 } for try await number in stream {     print(number, terminator: " ") } // Prints "1 2 3 4 5 "

## See Also

### Accessing an Asynchronous Sequence of Results

- [makeAsyncIterator()](swift/taskgroup/makeasynciterator().md)
- [allSatisfy(_:)](swift/taskgroup/allsatisfy(_:).md)
- [compactMap(_:)](swift/taskgroup/compactmap(_:)-944od.md)
- [compactMap(_:)](swift/taskgroup/compactmap(_:)-7mgj1.md)
- [contains(_:)](swift/taskgroup/contains(_:).md)
- [contains(where:)](swift/taskgroup/contains(where:).md)
- [drop(while:)](swift/taskgroup/drop(while:).md)
- [dropFirst(_:)](swift/taskgroup/dropfirst(_:).md)
- [filter(_:)](swift/taskgroup/filter(_:).md)
- [first(where:)](swift/taskgroup/first(where:).md)
- [flatMap(_:)](swift/taskgroup/flatmap(_:)-vhi3.md)
- [map(_:)](swift/taskgroup/map(_:)-58nsr.md)
- [map(_:)](swift/taskgroup/map(_:)-4a4kq.md)
- [max()](swift/taskgroup/max().md)
- [max(by:)](swift/taskgroup/max(by:).md)
