Home > Software engineering >  Iterating backwards with for-loop doesn't work
Iterating backwards with for-loop doesn't work

Time:10-29

I'm a newbie on Swift and I'm really confused about how to iterate backward with for-loop.

my array:

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

Trying for-loop that i googled:

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

Output: Terminated by signal 4

Another attempt that doesn't work:

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

what am i doing wrong?

CodePudding user response:

Both of them doesn't work because you start at arr.count, which is always an invalid index for an array. The last valid index is arr.count - 1, so changing the start of the stride/range to that will fix the problem.

If you want to iterate through the indices in reverse, you can just get the indices and reverse it:

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.

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

}

CodePudding user response:

You missed the point that array indices – in almost all programming languages – are zero based, so the last index is count - 1

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