我碰到一个需要成对迭代数组的问题。什么是最好的方法来做到这一点?或者,作为一种替代方法,将数组转换为数组对的最佳方式是什么(然后可以正常迭代)?Swift:配对元素的最佳方式是什么
这是我得到的最好的。它要求output
是一个var
,它不是很漂亮。有没有更好的办法?
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)
如果什么元素的您的数组数它甚至没有?最后一个元素将一直被丢弃。 –
假设有偶数个元素是安全的。 ( – Alexander