William Hu William Hu - 7 months ago 45
Swift Question

C-Style i++ for is deprecated in swift issue

I want to increment index at some point for this loop it prints 1,3,5 which is i want to. I get the warning

C-Style for statement is deprecated and ...



i know what it means.

for var index=0; index<5; index++ {
//If condition A == true
index++
//else without index++
print(index) // print 1, 3, 5
}


So i changed it to:

for var index in 0..<5 {
//If condition A == true
index += 1
//else without index++
print(index) // print 1,2,3,4,5 Should 1,3,5 from my side
}


I just wondering why index not mutable? Even though i have set it to
var
or any solutions for my issue.

Answer

The index is not mutable because

for var x in y { 
    ...
}

is equivalent to

for temp in y { 
    var x = temp
    ...
}

where the var just makes x a copy of temp. When you modify x, it won't modify the real index temp (This is also a reason why SE-0003 is introduced)


The C-style for loop can just be reduced to a while loop:

var index = 0
while index < 5 {
    if conditionA {
        index += 1
    }
    print(index)
    index += 1
}
Comments