I have this loop, decrementing an integer by division, in Swift 2.
for var i = 128; i >= 1 ; i = i/2 {
//do some thing
}
The C-style for loop is deprecated, so how can I convert this to Swift 3.0?
I have this loop, decrementing an integer by division, in Swift 2.
for var i = 128; i >= 1 ; i = i/2 {
//do some thing
}
The C-style for loop is deprecated, so how can I convert this to Swift 3.0?
I'll suggest that you should use a
while
loop to handle this scenario:MartinR's solution is very generic and useful and should be part of your toolbox.
Another approach is to rephrase what you want: the powers of two from 7 down to 0.
Quite general loops with a non-constant stride can be realized with
sequence
:i
is a constant and its scope is restricted to the loop body.$0 >= 2
instead ofi >= 1
), and the loop is always executed at least once, for the first value.One could also write a wrapper which resembles the C-style for loop more closely and does not have the listed disadvantages (inspired by Erica Sadun: Stateful loops and sequences):
and then use it as