【问题标题】:How to skip iterations of a for-in loop (Swift 3)如何跳过 for-in 循环的迭代(Swift 3)
【发布时间】:2017-04-21 21:41:50
【问题描述】:

是否可以在 Swift 3 中跳过 for-in 循环的迭代?

我想做这样的事情:

for index in 0..<100 {
    if someCondition(index) {
        index = index + 3 //Skip iterations here
    }
}

【问题讨论】:

    标签: swift swift3 for-in-loop


    【解决方案1】:

    最简单的方法是在 if 条件中使用continue

           for index in 1...100
           {
                if index == 5
                {
                   continue
                }
            print(index)//1 2 3 4 6 7 8 9 10
            }
    

    或者

    for index in 1...10 where index%2 == 0
    {
      print(index)//2 4 6 8 10
    }
    

    【讨论】:

    • 目前为止的正常方法。
    • 这很正常:)。
    • 这并不能解决问题,因为期望的结果是跳转索引 3 位。
    【解决方案2】:

    简单的while循环就可以了

    var index = 0
    
    while (index < 100) {
        if someCondition(index) {
            index += 3 //Skip 3 iterations here
        } else {
            index += 1
            // anything here will not run if someCondition(index) is true
        }
    }
    

    【讨论】:

    • 这将完美运行。对于这种情况,while 循环似乎是更好的选择。
    • while (index &lt; 100) { index += someCondition(index) ? 3 : 1 }
    • 哇 - 这让我节省了一个小时的思考时间......太明显了!
    【解决方案3】:

    Continue-statement 只会跳过一次,这不是要求的。

    while 循环也可以,但如果您不想使用它:

    var skipToIndex = 0
    
    for index in 0...100 {
    
        if index < skipToIndex {
            continue
        }
    
        if someCondition {
            skipToIndex = index + 3 //Skip three iterations
        }
    }
    

    【讨论】:

      【解决方案4】:

      无论是 for-in 的 .forEach,您始终拥有对当前评估项的引用。因此,如果您想继续迭代,您可以决定每个项目的基础。

      let numbers = [1,2,3,4,5,6,7]
      
      numbers.forEach {
          guard $0 != 3 else { return }
          print($0)
      }
      

      如果您的问题意味着如何停止,请查看“休息”。如果实际问题是找到特定项目时停止,请查看 .filter。

      【讨论】:

      • 感谢您提供答案。您能否编辑您的答案以包括对您的代码的解释?这将有助于未来的读者更好地了解正在发生的事情,尤其是那些刚接触该语言并难以理解概念的社区成员。
      猜你喜欢
      • 1970-01-01
      • 2021-08-23
      • 1970-01-01
      • 1970-01-01
      • 2021-04-15
      • 2021-11-15
      • 2014-08-30
      相关资源
      最近更新 更多