How to skip an index in a for loop in Swift

I try to skip in the random condition that if true, skip the loop, but the results will print all the elements 0,1,2,3,4 I know that in Java, if the index increases, the index will skip, but this does not happen. Swift.?

Update: this is a simplified version of some program that I wrote, print() should happen immediately after each cycle, and the index ONLY increases 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 } } 
+5
source share
7 answers

The index automatically increases in the loop, you can skip the index with the where clause:

 for index in 0..<5 where index != 2 { print(index) } 
+13
source

Try the following:

 for var index in 0..<5 { if index == 2 { continue } print(index)//this prints 0,1,3,4 } 
+6
source

In your for-loop:

 for var index in 0..<5 { if index != 2{ print(index) } } 
+2
source
 for var index in 0..<5 { if index == 2 { //dont do anything } else { print(index) } } 

Isn't it that simple?

+1
source

It works. Not sure if this is the best way to do this.

 var skip = false for var index in 0..<5 { if (skip) { skip = false continue } print(index) if index == 2 { skip = true } } 
+1
source
 (0..<5).filter({$0 != 2}).forEach{ x in print(x)} 

(or) when the condition is unknown,

 (0..<5).filter(isNumber2).forEach{ x in print (x)} 

Note. isNumber2 is an external function that returns a boolean after evaluating a condition on a number. Your implementation of this function may vary.

 var isNumber2: (Int) -> (Bool) = { return $0 != 2} 
0
source

for the index at 0 .. <5 where (indicate your condition here) {print (index)}

If the condition is to skip index 3, for the index at 0 .. <5, where index! = 3 {print (index)}

0
source

Source: https://habr.com/ru/post/1262517/


All Articles