【发布时间】:2017-04-21 21:41:50
【问题描述】:
是否可以在 Swift 3 中跳过 for-in 循环的迭代?
我想做这样的事情:
for index in 0..<100 {
if someCondition(index) {
index = index + 3 //Skip iterations here
}
}
【问题讨论】:
标签: swift swift3 for-in-loop
是否可以在 Swift 3 中跳过 for-in 循环的迭代?
我想做这样的事情:
for index in 0..<100 {
if someCondition(index) {
index = index + 3 //Skip iterations here
}
}
【问题讨论】:
标签: swift swift3 for-in-loop
最简单的方法是在 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
}
【讨论】:
简单的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
}
}
【讨论】:
while (index < 100) { index += someCondition(index) ? 3 : 1 }
Continue-statement 只会跳过一次,这不是要求的。
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 $0 != 3 else { return }
print($0)
}
如果您的问题意味着如何停止,请查看“休息”。如果实际问题是找到特定项目时停止,请查看 .filter。
【讨论】: