I came across a problem that required iterating over an array in pairs. What\'s the best way to do this? Or, as an alternative, what\'s the best way of transforming an Array
You don't need a custom type, like PairIterator
as the above answers prescribe. Getting a paired sequence is a one-liner:
let xs = [1, 2, 3]
for pair in zip(xs, xs.dropFirst()) {
print(pair) // (1, 2) (2, 3)
}
If you intend to reuse that, you can place a pairs method inside an extension:
extension Sequence {
func pairs() -> AnySequence<(Element, Element)> {
AnySequence(zip(self, self.dropFirst()))
}
}