简体   繁体   English

使用 for 循环向后迭代不起作用

[英]Iterating backwards with for-loop doesn't work

I'm a newbie on Swift and I'm really confused about how to iterate backward with for-loop.我是 Swift 的新手,我真的很困惑如何使用 for 循环向后迭代。

my array:我的阵列:

let arr = ["a", "b", "c"]

Trying for-loop that i googled:尝试我用谷歌搜索的 for 循环:

for i in stride(from: arr.count, through: 0, by: -1) {
print(arr[i]) }

Output: Terminated by signal 4输出:由信号 4 终止

Another attempt that doesn't work:另一种无效的尝试:

for i in arr.count...0 {
    print(arr[i])
}

what am i doing wrong?我究竟做错了什么?

Both of them doesn't work because you start at arr.count , which is always an invalid index for an array.它们都不起作用,因为您从arr.count开始,这始终是数组的无效索引。 The last valid index is arr.count - 1 , so changing the start of the stride/range to that will fix the problem.最后一个有效索引是arr.count - 1 ,因此将步幅/范围的开始更改为该索引将解决问题。

If you want to iterate through the indices in reverse, you can just get the indices and reverse it:如果要反向遍历索引,只需获取indices并将其reverse

for i in arr.indices.reversed() {
    let element = arr[i]
}

Alternatively, you can use enumerated().reversed() , but note that reversed() here will first create an extra array to hold the reversed indices and elements, which means that you will be looping through arr an extra time.或者,您可以使用enumerated().reversed() ,但请注意,这里的reversed()将首先创建一个额外的数组来保存反向索引和元素,这意味着您将额外循环arr一次。

for (i, element) in arr.enumerated().reversed() {

}

You missed the point that array indices – in almost all programming languages – are zero based, so the last index is count - 1你忽略了数组索引——在几乎所有编程语言中——都是从零开始的,所以最后一个索引是count - 1

for i in stride(from: arr.count - 1, through: 0, by: -1) {
    print(arr[i])
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM