Skip to content

Commit d91723b

Browse files
authored
Create Suffix.md (#82)
Guide for suffix(while: ) function
1 parent 63311ae commit d91723b

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Guides/Suffix.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Suffix
2+
3+
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Suffix.swift) |
4+
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/SuffixTests.swift)]
5+
6+
7+
This function returns a subsequence containing the elements from the end of the collection until predicate returns `false` and skipping the remaining elements.
8+
9+
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`
10+
```swift
11+
(0...10).suffix(while: { $0 > 5 } // == [6,7,8,9,10]
12+
```
13+
14+
15+
## Detailed Design
16+
17+
The `suffix(while:)` function is added as a method on an extension of `BidirectionalCollection`.
18+
19+
20+
```swift
21+
extension BidirectionalCollection {
22+
23+
public func suffix(while predicate: (Element) throws -> Bool) rethrows -> SubSequence
24+
}
25+
```
26+
27+
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.
28+
29+
### Complexity
30+
31+
Calling this method is O(*n*), where *n* is the length of the collection.
32+
33+
34+
### Naming
35+
36+
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.
37+
38+
39+

0 commit comments

Comments
 (0)