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

2019-01-18 06:47发布

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)

3条回答
小情绪 Triste *
2楼-- · 2019-01-18 07:05

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)

}
查看更多
Animai°情兽
3楼-- · 2019-01-18 07:07

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)]
查看更多
看我几分像从前
4楼-- · 2019-01-18 07:14

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)]
查看更多
登录 后发表回答