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 into an Array of pairs (which could then be iterated normally)?
Here's the best I got. It requires output
to be a var
, and it's not really pretty. Is there a better way?
let input = [1, 2, 3, 4, 5, 6]
var output = [(Int, Int)]()
for i in stride(from: 0, to: input.count - 1, by: 2) {
output.append((input[i], input[i+1]))
}
print(output) // [(1, 2), (3, 4), (5, 6)]
// let desiredOutput = [(1, 2), (3, 4), (5, 6)]
// print(desiredOutput)
You can map the stride instead of iterating it, that allows to get the result as a constant:
If you only need to iterate over the pairs and the given array is large then it may be advantageous to avoid the creation of an intermediate array with a lazy mapping:
I don't think this is any better than Martin R's, but seems the OP needs something else...
Here's a version of @OOPer's answer that works with an odd number of elements in your list. You can leave off the conformance to
CustomStringConvertible
if you like, of course. But it gives prettier output for this example. : )