跳转到 for-in 循环中的索引

Skip to index in for-in loop

假设我有一个这样的 for-in 循环:

for index in 1...5 {

}

假设我发现在索引 2 处,由于某些情况我想跳到索引 4。以下不起作用:

for index in 1...5 {
    if index == 2 {
        index = 4
    }
}

因为它给我以下错误:

Cannot assign to value: 'index' is a 'let' constant

如何修改索引的位置以跳到索引 4?

在 for 循环中,您不能实时跳转索引 - 也就是说,如果您发现循环开始后需要跳过迭代,则不能。但是您可以使用 continue 退出迭代。例如:

var skip = 0
for i in 1...5 {
    if i < skip { continue }
    print(i)
    if i == 2 { skip = 4}
}

但是,在这种情况下,while 循环可能会让您更满意。

var i = 1
while i <= 5 {
    print(i)
    i += 1
    if i == 3 { i = 4 }
}

另一种可能性是将原来的 for 循环展开为 while 循环:

var r = (1...5).makeIterator()
while let i = r.next() {
    print(i)
    if i == 2 { r.next() }
}

这些都是打印方式1,2,4,5