Reputation: 215
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
}
}
Upvotes: 8
Views: 6429
Reputation: 11
Be it a .forEach for for-in, you have allways a reference to the current evaluated item. So you can decide on a per item base if you want to continue the iteration.
let numbers = [1,2,3,4,5,6,7]
numbers.forEach {
guard $0 != 3 else { return }
print($0)
}
If your question meant how to stop then have a look on 'break'. If the actual question is about stop when found a specific item, then have a look on .filter.
Upvotes: -1
Reputation: 161
Continue-statement will only skip once, which is not what was asked for.
A while-loop will work, but if you prefer not to use one:
var skipToIndex = 0
for index in 0...100 {
if index < skipToIndex {
continue
}
if someCondition {
skipToIndex = index + 3 //Skip three iterations
}
}
Upvotes: 1
Reputation: 15758
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
}
Upvotes: 20
Reputation: 46598
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
}
}
Upvotes: 10