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

大憨熊 提交于 2019-11-27 02:53:29

问题


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)

回答1:


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)

}



回答2:


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)]



回答3:


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)]


来源:https://stackoverflow.com/questions/40841663/swift-whats-the-best-way-to-pair-up-elements-of-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!