Skip to content

Latest commit

 

History

History
59 lines (41 loc) · 1.87 KB

Windows.md

File metadata and controls

59 lines (41 loc) · 1.87 KB

Windows

[Source | Tests]

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.