我遇到了一个需要迭代数组成对的问题。最好的方法是什么?或者,作为替代方案,将数组转换为成对的数组,然后正常迭代它们的最佳方式是什么?
这是我找到的最佳方法。它需要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)