fumoboy007 fumoboy007 - 3 months ago 22
Swift Question

Iterate over collection two at a time in Swift

Say I have an array

[1, 2, 3, 4, 5]
. How can I iterate two at a time?

Iteration 1: (1, 2)
Iteration 2: (3, 4)
Iteration 3: (5, nil)

Answer

You can use a progression loop called stride(to:, by:) to iterate over your elements every n elements:

let array = Array(1...5)

var pairs:[(Int?,Int?)] = []

for index in 0.stride(to: array.count, by: 2) {
    pairs.append((array[index], index < array.count.predecessor() ? array[index.successor()]: nil))
}

Xcode 8 beta 6 • Swift 3

for index in stride(from: 0, to: array.count, by: 2) {
    pairs.append((array[index], index < array.count-1 ? array[index+1]: nil))
}