Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip iterations of a for-in loop (Swift 3)

Is it possible to skip iterations of a for-in loop in Swift 3?

I want to do something like this:

for index in 0..<100 {
    if someCondition(index) {
        index = index + 3 //Skip iterations here
    }
}
like image 290
MyBikeIsAwesome Avatar asked Dec 07 '16 03:12

MyBikeIsAwesome


2 Answers

The easiest way is using continue within the if condition

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

Or

for index in 1...10 where index%2 == 0
{
  print(index)//2 4 6 8 10
}
like image 110
RajeshKumar R Avatar answered Sep 29 '22 04:09

RajeshKumar R


Simple while loop will do

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
    }
}
like image 23
Bryan Chen Avatar answered Sep 29 '22 06:09

Bryan Chen