How to write a non-C-like for-loop in Swift 2.2+?

Viewed 2173

I have updated Xcode (7.3) and there are a lot of changes; C-like for expressions will be deprecated. For a simple example,

for var i = 0;  i <= array.count - 1;  i++
 {
      //something with array[i]
 } 

How do I write this clear and simple C-like for-loop to be compliant with the new changes?

for var i = 0, j = 1;  i <= array.count - 2 && j <= array.count - 1;  i++, j++
{
     //something with array[i] and array[j]
}  

Update. One more variant

for var i = 0; i <= <array.count - 1; i++
{
    for var j = i + 1; j <= array.count - 1; j++
    {
        //something with array[i] and array[j]
    }
}

And more ...

for var i = 0, j = 1, g = 2;  i <= array.count - 3 && j <= array.count - 2 &&   g <= array.count - 1;  i++, j++, g++
{
     //something with array[i] and array[j] and array[g]
} 

Update2 After several suggestions for me while loop is preferable universal substitution for all cases more complicated than the simple example of C-like for-loop (suitable for for in expression). No need every time to search for new approach.
For instance: Instead of

for var i = 0; i <= <array.count - 1; i++
{
    for var j = i + 1; j <= array.count - 1; j++
    {
        //something with array[i] and array[j]
    }
}

I can use

var i = 0
while i < array.count
{
    var j = i + 1
    while j < array.count
    {
        //something with array[i] and array[j]
        j += 1
    }
    i += 1
}
7 Answers
Related