What is the term for the "current/temporary element" inside a For-loop?

I want to know the name of the "temporary variable" that you access inside a for-loop. It's not really language-specific, but here's my code in Swift:

let array = [1, 2, 3]
for number in array {
    print(number) /// what is this?
}

What is number, the "temporary variable" that is different in each iteration, known as?

Here are my attempts at describing it.

  • The current iteration's element
  • The current element

Then, what if I was looping over the array's indices? How would I refer to number in this case?

let list = [1, 2, 3]
for i in 0..<list.count {
    let number = list[i] /// what is this?
    print(number)
}

My attempts:

  • The element of the list array at the current iteration's index
  • The element of the list array at the loop's current iteration's index

1 answer

  • answered 2021-05-15 06:12 Raja Kishan

    let's take one example.

    let array = [1, 2, 3]
    for number in array {
        print(number)
    }
    

    for the above case, the loop will print each number (element/Object) of the array(Not the index of the element).

    It means if the array is [a,b,c,d], it will print abcd

    For the second case, you are iterating loop over a range of array and then get the element based on an index

    let list = [1, 2, 3]
    for i in 0..<list.count {
        let number = list[i] /// what is this?
        print(number)
    }
    

    The above example, i is referred to the index of an array value and let number = list[i] code will give you an element at the i index.

    In last, If you want both indexes with the element within a single loop. You can use .enumerated()

    Here is one example

    let array = [1, 2, 3]
    for (index, number) in array.enumerated() {
        print("Array object/ Element Index :- ", index)
        print("Array object/ Element :- ", number)
    }