且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Swift:配对数组元素的***方式是什么?

更新时间:2023-02-05 13:19:22

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)

}