How to change C-style for loop to Swift

I am looking at a video tutorial on another site that is using and older version of Swift. I get the error message “C-style for statement has been removed in Swift 3” . Is there an app to convert C for statements, or can someone type the solution?

The code is written like this:

               for var i = array.count - 1;  i > 0; i--  {
                      let j = arc4random_uniform(UInt32(i - 1));
                }

Thanks in advance!

Use a while loop instead of a for loop.

var i = array.count - 1
while i > 0 {
    let j = arc4random_uniform(UInt32(i - 1))
    i = i - 1
}

Thanks, I will try that. I seen some forums and some people use for in loop. Is that better?

Use a for in loop when you want to go through all the items in a collection, such as an array, and do something on each item. If you didn’t use i’s current value in your call to arc4random, you could use a for in loop. You could go through each item in the array in the loop and generate a random number.

for item in array {
    let j = item.generateRandomNumber()
}

In your example you make heavy use of the i variable. You use i to generate the random number. You also use i’s value to check if you should stop running the loop. In this case you need a while loop to check that i is greater than zero. Swift for loops don’t let you test a condition at the start of the loop so a for in loop would not work.

maybe you can try to iterate on reversed closed range:

 for i in (0..<array.count).reversed() {
    print(i)
}

or
on reversed enumerated collection:

for (index,value) in array.enumerated().reversed() {
                   print(index)
 }

This topic was automatically closed after 166 days. New replies are no longer allowed.