Ian Solomein
Ian Solomein

Reputation: 67

Swift for in loop. Constant or variable?

Apple in their documentation says

for index in 1...5 {
   print("\(index) times 5 is \(index * 5)")
}

“In the example above, index is a constant whose value is automatically set at the start of each iteration of the loop. As such, index does not have to be declared before it is used. It is implicitly declared simply by its inclusion in the loop declaration, without the need for a let declaration keyword.

Why do they call index a constant if it's value changes inside the loop ?

Excerpt From: Apple Inc. “The Swift Programming Language (Swift 5.2)”. Apple Books. https://books.apple.com/ru/book/the-swift-programming-language-swift-5-2/id881256329?l=en

Upvotes: 1

Views: 700

Answers (1)

Sweeper
Sweeper

Reputation: 271905

It's a constant because you can't change it inside the loop. The compiler translates the for loop to something to the effect of:

var iterator = (1...5).makeIterator()
while true {
    if let index = iterator.next() {
        // the loop body goes here
    } else {
        break
    }
}

index is constant, but a new index gets declared every iteration.

Upvotes: 2

Related Questions