Why does for loop require var while for..in does not allow use of var?
for loop
for var index = 0; index < 10; i++ {
}
for..in loop
for index in "test" {
}
instead of:
for var index in "test" {
}
The Swift documentation sums it up pretty nicely:
indexis a constant whose value is automatically set at the start of each iteration of the loop. As such, it 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.
In other words, the variable used in a for/in loop can only be a constant; thus, there's really no need to require that let be used.
The variable(s) used in a "traditional" for loop, however, can be variables or constants, so var or let is required. (Generally, they will be variables, but it is possible to use a constant in a for loop.) They can also be declared outside of the for loop (i.e., before it) and still used in the for loop. Because of this flexibility, you are required to declare it as a constant or variable.
The compiler expands for x in 0..<5 to the following:
var g = (0..<5).generate() {
while let x = g.next() {
// Use x in loop body
}
Every time around the loop, x is a freshly declared variable, the value of unwrapping the next result from calling next on the generator.
Now, that while can be rewritten in this fashion:
while var x = g.next() {
// use x here
}
I guess for this reason, for...in doesn't support the var syntax for declaring the loop counter so that it doesn't give you the wrong impression that x is mutable.
next() value of the generator each time. In my opinion, I think the Swift designers didn't want to include the let or var keyword for the loop counter to avoid misconceptions about what can be done with it i.e. modify it which is a strict no-no.g, which is returned by the generate() method is the same instance throughout the course of the loop but I think x is freshly created for every single iteration. I don't think the compiler reuses the same x instance. Having said that, I'm not sure whether it would be dependent on next() returning an instance of class/ enum/ struct.
indexis immutable (and cannot be anything but immutable). But this still isn't the question you're asking. You're asking whyvar(and alsoletwhich is perfectly valid in your "traditional" loop example) are not necessary. And as I've pointed out, it's still purely opinion based as to why it'sfor index in someArrayversus requiringfor let index in someArray. Only a language designer can chime in on the actual question asked here (why theletisn't used).