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
}
}
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.
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 .
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.
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 .
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)
}
Please try this one:
for var index in 0..<5 {
if index == 2 {
continue
}
print(index)//this prints 0,1,3,4
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With