Swift:For Loop 按大于 1 的索引遍历枚举数组

标签 swift for-in-loop stride enumerated

有没有一种方法可以使用 .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)")
}

最佳答案

您有两种方法可以获得所需的输出。

  1. 仅使用 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])")
    }
    
  2. enumerated()for inwhere 结合使用。

    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/

相关文章:

swift - 当我从一个节点切换到另一个节点时,是否应该删除所有 SKSpriteNodes 和 Labels

swift - Swift 5 中一个简单的字符串处理函数

swift - 何时使用 forEach(_ :) instead of for in?

OpenGL 3/4 glVertexAttribPointer 步长和偏移计算错误

python - 识别Python中滚动窗口内最大值之前出现的最小值

swift - Realm 是否支持 Swift 中的计算属性

ios - "UIPickerView"中的多列

ios - 在 for in 循环中修改数据结构是否安全?

Python for-in-loop 停止迭代从 for-in-loop 创建的列表对象

iOS( swift ): Changing UILabel text with a for loop