如何在Swift中跳过for循环中的索引

mir*_*doh 12 iteration for-loop ios swift

我试图跳过随机条件,如果为true,将跳过循环,但结果是打印0,1,2,3,4 我在Java中知道的所有元素,如果索引增加索引将跳过,但这不会发生Swift.

更新:这是我编写的某个程序的简化版本,print()必须在每个循环之后立即发生,并且索引仅在某些未知条件下递增,我希望它的行为类似于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
  }
}
Run Code Online (Sandbox Code Playgroud)

vad*_*ian 25

索引在循环中自动递增,您可以跳过带有where子句的索引:

for index in 0..<5 where index != 2 {
    print(index)
}
Run Code Online (Sandbox Code Playgroud)

  • 如果$ 0!= 2是未知条件怎么办? (2认同)

Sar*_*ngh 24

请试试这个:

for var index in 0..<5 {

  if index == 2 {
     continue
  }
  print(index)//this prints 0,1,3,4
}
Run Code Online (Sandbox Code Playgroud)


mir*_*doh 5

这可行。不知道这是否是最好的方法。

var skip = false
for var index in 0..<5 {
  if (skip) {
    skip = false
    continue
  }

  print(index)
  if index == 2 {
      skip = true
  }
}
Run Code Online (Sandbox Code Playgroud)