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

前端 未结 4 900
独厮守ぢ
独厮守ぢ 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 11:15

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

    struct PairIterator: 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)]
    

提交回复
热议问题