Files
swift-algorithms/Guides/Suffix.md
Tim Vermeulen c5ea9e3e36 Prepare for Swift Algorithms 1.0 (#167)
* Rename types to include a Sequence or Collection suffix, and clean up some guides

* Various refactors

* Replace `validateIndexTraversals` test method with `IndexValidator` type

* Add LazySequenceProtocol to StridingSequence, StridingCollection

* Update the Numerics dependency to 1.0

* Set `IndexedCollection.Indices` to `Base.Indices`

* Remove deprecations

* Update the changelog/README for the 1.0.0 release

* Fix compiler error on Linux

* Rename `WindowsCollection` to `WindowsOfCountCollection`
2021-09-09 01:01:36 +02:00

1.4 KiB

Suffix

[Source | Tests]

This function returns a subsequence containing the elements from the end of the collection until predicate returns false and skipping the remaining elements.

This example uses suffix(while: ) to iterate through collection of integers from the end until the predicate returns false, in this case when $0 <= 5

(0...10).suffix(while: { $0 > 5 } // == [6,7,8,9,10]

Detailed Design

The suffix(while:) function is added as a method on an extension of BidirectionalCollection.

extension BidirectionalCollection {
    public func suffix(while predicate: (Element) throws -> Bool) rethrows -> SubSequence
}

This method requires BidirectionalCollection for an efficient implementation which visits as few elements as possible. Swift's protocol allows for backward traversal of a collection as well as access to last property of a collection.

Complexity

Calling this method is O(n), where n is the length of the collection.

Naming

The function's name resembles that of an existing Swift function prefix(while:), which performs same operation however in the forward direction of the collection. Hence, as this function traverses from the end of the collection, suffix(while:) is an appropriate name.