Fix warning "C-style for Statement is deprecated" in Swift 3

Solution 1:

C-style for loop has been deprecated in Swift 3. You can continue using it for a while, but they will certainly disappear in the future.

You can rewrite your loop to Swift's style:

for i in 0..<len {
    let length = UInt32 (letters.length)
    let rand = arc4random_uniform(length)
    randomString.appendFormat("%C", letters.characterAtIndex(Int(rand)))
}

Since you don't use i at all in the loop's body, you can replace it with:

for _ in 0..<len {
    // do stuffs
}

Solution 2:

This BLOG saved my life.

INCREMENTING

for i in 0 ..< len {

}

DECREMENTING

for i in (0 ..< len).reverse() {

}

NON-SEQUENTIAL INDEXING

Using where

for i in (0 ..< len) where i % 2 == 0 {

}

Using striding to or through

for i in 0.stride(to: len, by: 2) {

}

Solution 3:

in Swift 3 it's been an error

some general replacement was posted and just add

For Swift 3 and need to change the "index"

for var index in stride(from: 0, to: 10, by: 1){}

Solution 4:

I've had success with the following. You can use the for loop as follows - note that the for loop is inclusive so you may need to check that len is actually greater than 0:

for i in 0...len - 1 {
  let length = UInt32 (letters.length)
  let rand = arc4random_uniform(length)
  randomString.appendFormat("%C", letters.characterAtIndex(Int(rand)))
}

Or you can use this:

for i in 0 ..< len {
  let length = UInt32 (letters.length)
  let rand = arc4random_uniform(length)
  randomString.appendFormat("%C", letters.characterAtIndex(Int(rand)))
}

BTW it appears XCode 7.x does help you to get there but it's a two step process. First you have to change your increment operator from (say) i++ to i += 1 and then XCode warning helps you modify the loop.