有没有一种方法可以使用 .enumerated() 和 stride 在索引大于 1 的字符串数组中使用 for-in 循环,以保留索引和值?
例如,如果我有数组
var testArray2: [String] = ["a", "b", "c", "d", "e"]
我想通过使用 testArray2.enumerated() 并使用 stride by 2 来循环输出:
0, a
2, c
4, e
理想情况下是这样的;但是,此代码将不起作用:
for (index, str) in stride(from: 0, to: testArray2.count, by: 2){
print("position \(index) : \(str)")
}
最佳答案
您有两种方法可以获得所需的输出。
仅使用
stride
var testArray2: [String] = ["a", "b", "c", "d", "e"] for index in stride(from: 0, to: testArray2.count, by: 2) { print("position \(index) : \(testArray2[index])") }
将
enumerated()
与for in
和where
结合使用。for (index,item) in testArray2.enumerated() where index % 2 == 0 { print("position \(index) : \(item)") }
关于Swift:For Loop 按大于 1 的索引遍历枚举数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43602259/