如何跳过for-in循环的迭代(Swift 3)

问题描述 投票:1回答:2

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

我想做这样的事情:

for index in 0..<100 {
    if someCondition(index) {
        index = index + 3 //Skip iterations here
    }
}
swift swift3 for-in-loop
2个回答
5
投票

简单的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
    }
}

8
投票

最简单的方法是在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
}
© www.soinside.com 2019 - 2024. All rights reserved.