'Swift: What's the best way to pair up elements of an Array

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)


Solution 1:[1]

This is now available as

Sequence.chunks(ofCount: 2) of the swift-algorithms package

for chunk in input.chunks(ofCount: 2) {
    print(chunk)
}

Solution 2:[2]

You can map the stride instead of iterating it, that allows to get the result as a constant:

let input = [1, 2, 3, 4, 5, 6]

let output = stride(from: 0, to: input.count - 1, by: 2).map {
    (input[$0], input[$0+1])
}

print(output) // [(1, 2), (3, 4), (5, 6)]

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:

for (left, right) in stride(from: 0, to: input.count - 1, by: 2)
    .lazy
    .map( { (input[$0], input[$0+1]) } ) {

    print(left, right)

}

Solution 3:[3]

I don't think this is any better than Martin R's, but seems the OP needs something else...

struct PairIterator<C: IteratorProtocol>: IteratorProtocol {
    private var baseIterator: C
    init(_ iterator: C) {
        baseIterator = iterator
    }

    mutating func next() -> (C.Element, C.Element)? {
        if let left = baseIterator.next(), let right = baseIterator.next() {
            return (left, right)
        }
        return nil
    }
}
extension Sequence {
    var pairs: AnySequence<(Self.Iterator.Element,Self.Iterator.Element)> {
        return AnySequence({PairIterator(self.makeIterator())})
    }
}

input.pairs.forEach{ print($0) }

let output = input.pairs.map{$0}
print(output) //->[(1, 2), (3, 4), (5, 6)]

Solution 4:[4]

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. : )

struct Pair<P: CustomStringConvertible>: CustomStringConvertible {
    let left: P
    let right: P?

    var description: String {
        if let right = right {
            return "(\(left.description), \(right.description)"
        }
        return "(\(left.description), nil)"
    }
}

struct PairIterator<C: IteratorProtocol>: IteratorProtocol where C.Element: CustomStringConvertible {
    private var baseIterator: C
    init(_ iterator: C) {
        baseIterator = iterator
    }

    mutating func next() -> Pair<C.Element>? {
        if let left = baseIterator.next() {
            return Pair(left: left, right: baseIterator.next())
        }
        return nil
    }
}
extension Sequence where Element: CustomStringConvertible {
    var pairs: AnySequence<Pair<Self.Element>> {
        return AnySequence({PairIterator(self.makeIterator())})
    }
}

let input: [Int] = [1,2,3,4,5,6,7]
print(input.pairs)
print(Array(input.pairs))


//output:
AnySequence<Pair<Int>>(_box: Swift._SequenceBox<Swift._ClosureBasedSequence<__lldb_expr_27.PairIterator<Swift.IndexingIterator<Swift.Array<Swift.Int>>>>>)
[(1, 2, (3, 4, (5, 6, (7, nil)]

Solution 5:[5]

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()))
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 OOPer
Solution 4 Daniel R
Solution 5 Jake Bromberg