-1

Is there a standard library solution or a package for iterating over an array where on every iteration, instead of getting an element, you get a tuple of one element and the next element?

In other words, you get a window covering two (or more) elements and on every iteration the window slides one element over. That's what I think this solution for Python is (not sure).

Here's my kludge solution for a window of size 2:

for index in array.indices.dropLast() {
    let a = array[index]
    let b = array[index + 1]
}

The number of iterations in this case would be array.count - 1 and every element would occur twice, except for the first and last elements.

It seems to me like there ought to be a standard, generic solution for this -- something like for (a, b) in array.slidingWindow(of: 2) { ... } -- but I couldn't find one.

hawk
  • 2,655
  • 2
  • 16
  • 11
  • 1
    Does [this](https://stackoverflow.com/questions/49476485/swift-loop-over-array-elements-and-access-previous-and-next-elements) answer your question? – Sweeper Oct 18 '22 at 17:03

1 Answers1