* 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`
1.9 KiB
Windows
Break a collection into overlapping subsequences where elements are slices from the original collection.
The windows(ofCount:) method takes a size as a parameter and returns a
collection of subsequences. Each element of the returned collection is a
successive overlapping slice of the given size.
let swift = "swift"
let windowed = swift.windows(ofCount: 2)
// Array(windowed) == [ "sw", "wi", "if", "ft" ]
Detailed Design
The windows(ofCount:) method is added as an extension Collection method:
extension Collection {
public func windows(ofCount count: Int) -> WindowsOfCountCollection<Self>
}
If a size larger than the collection's length is specified, the returned collection is empty.
[1, 2, 3].windows(ofCount: 5).isEmpty // true
The resulting WindowsOfCountCollection type is a collection, with conditional
conformance to the BidirectionalCollection, RandomAccessCollection, and
LazySequenceProtocol protocols when the base collection conforms.
Complexity
The call to windows(ofCount: k) is O(1) if the collection conforms to
RandomAccessCollection, otherwise O(k). Access to each successive window is
O(1).
Naming
The method and type name take their names from the sliding windows algorithm.
The ofCount parameter label was chosen to create a consistent feel with other
APIs in the Algorithms package, specifically with combinations(ofCount:)
and permutations(ofCount:).
Comparison with other languages
rust has
std::slice::Windows which is a method available on slices. It has the same
semantics as described here.