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

前端 未结 4 877
独厮守ぢ
独厮守ぢ 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:54

    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)
    
    }
    
    0 讨论(0)
  • 2020-11-30 10:54

    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)]
    
    0 讨论(0)
  • 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()))
        }
    }
    
    0 讨论(0)
  • 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<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)]
    
    0 讨论(0)
提交回复
热议问题