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

前端 未结 4 893
独厮守ぢ
独厮守ぢ 2020-11-30 10:42

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

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 10:57

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

提交回复
热议问题