如何跳过 for-in 循环的迭代 (Swift 3)
How to skip iterations of a for-in loop (Swift 3)
是否可以跳过 Swift 3 中 for-in 循环的迭代?
我想做这样的事情:
for index in 0..<100 {
if someCondition(index) {
index = index + 3 //Skip iterations here
}
}
简单的 while 循环就可以了
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
}
}
最简单的方法是在 if 条件
中使用 continue
for index in 1...100
{
if index == 5
{
continue
}
print(index)//1 2 3 4 6 7 8 9 10
}
或
for index in 1...10 where index%2 == 0
{
print(index)//2 4 6 8 10
}
Continue 语句只会跳过一次,这不是所要求的。
while 循环可以工作,但如果您不想使用 while 循环:
var skipToIndex = 0
for index in 0...100 {
if index < skipToIndex {
continue
}
if someCondition {
skipToIndex = index + 3 //Skip three iterations
}
}
无论是 for-in 的 .forEach ,您总是有一个对当前评估项目的引用。因此,如果您想继续迭代,您可以决定每个项目的基础。
let numbers = [1,2,3,4,5,6,7]
numbers.forEach {
guard [=10=] != 3 else { return }
print([=10=])
}
如果您的问题是如何停止,请查看 'break'。如果实际问题是关于找到特定项目时停止,请查看 .filter。
是否可以跳过 Swift 3 中 for-in 循环的迭代?
我想做这样的事情:
for index in 0..<100 {
if someCondition(index) {
index = index + 3 //Skip iterations here
}
}
简单的 while 循环就可以了
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
}
}
最简单的方法是在 if 条件
中使用continue
for index in 1...100
{
if index == 5
{
continue
}
print(index)//1 2 3 4 6 7 8 9 10
}
或
for index in 1...10 where index%2 == 0
{
print(index)//2 4 6 8 10
}
Continue 语句只会跳过一次,这不是所要求的。
while 循环可以工作,但如果您不想使用 while 循环:
var skipToIndex = 0
for index in 0...100 {
if index < skipToIndex {
continue
}
if someCondition {
skipToIndex = index + 3 //Skip three iterations
}
}
无论是 for-in 的 .forEach ,您总是有一个对当前评估项目的引用。因此,如果您想继续迭代,您可以决定每个项目的基础。
let numbers = [1,2,3,4,5,6,7]
numbers.forEach {
guard [=10=] != 3 else { return }
print([=10=])
}
如果您的问题是如何停止,请查看 'break'。如果实际问题是关于找到特定项目时停止,请查看 .filter。