Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip an index in a for loop in Swift

Tags:

I'm trying to skip in a random condition that if true, will skip a loop, but results are printing all elements 0,1,2,3,4 I know in Java if index is incremented index will skip, but this is not happening Swift.?

Update: this is a simplified version of some program I wrote, the print() has to be happen right after each loop, and index is ONLY incremented in some unknown conditions, I want it to behave like JAVA.

for var index in 0..<5 {
  print(index)//this prints 0,1,2,3,4, this must happen right after for loop
  if some unknown condition {
      index+=1
  }
}
like image 811
miracle-doh Avatar asked Jan 09 '17 08:01

miracle-doh


People also ask

How do you skip something in a for loop?

You can use the continue statement if you need to skip the current iteration of a for or while loop and move onto the next iteration.

How do you skip a value in a while loop?

The continue statement is used inside a for loop or a while loop. The continue statement skips the current iteration and starts the next one. Typically, you use the continue statement with an if statement to skip the current iteration once a condition is True .

How do you skip an iteration?

The continue statement (with or without a label reference) can only be used to skip one loop iteration. The break statement, without a label reference, can only be used to jump out of a loop or a switch.

How do I iterate a list in Swift?

Swift provides for-in loop for this kind of job. You use the for-in loop to iterate over a sequence, such as items in an array. This example uses a for-in loop to iterate over the subviews and set their translatesAutoresizingMaskIntoConstraints to false .


2 Answers

The index is automatically incremented in the loop, you can skip an index with a where clause:

for index in 0..<5 where index != 2 {
    print(index)
}
like image 107
vadian Avatar answered Oct 22 '22 00:10

vadian


Please try this one:

for var index in 0..<5 {

  if index == 2 {
     continue
  }
  print(index)//this prints 0,1,3,4
}
like image 21
Sarabjit Singh Avatar answered Oct 22 '22 01:10

Sarabjit Singh