Swift:配对数组元素的最佳方式是什么 [英] Swift: What's the best way to pair up elements of an Array

查看:39
本文介绍了Swift:配对数组元素的最佳方式是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个需要成对迭代数组的问题.做到这一点的最佳方法是什么?或者,作为替代方案,将 Array 转换为成对数组(然后可以正常迭代)的最佳方法是什么?

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

这是我得到的最好的.它要求 output 是一个 var,它不是很漂亮.有没有更好的办法?

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)

推荐答案

现在可以作为

Sequence.chunks(ofCount: 2)swift-algorithms

for (left, right) in input.chunks(ofCount: 2) {
    print(left, right)
}

这篇关于Swift:配对数组元素的最佳方式是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆