Swift - for loop control variable

Introduction

The for loop control variable i is not accessible after the loop exits, as it is defined within the For loop construct:

Demo

//print from 0 to 4
for var i = 0; i<5; i++ {
    print(i)//from   ww w. j a v  a  2 s  .c o m
}
//print(i)   //i is not defined

If you want i to be visible after the loop, create it first, before using it in the loop:

Demo

//print from 0 to 4
var i:Int/*from w  w w . j av a 2 s  . c  o m*/
for  i  = 0; i<5; i++ {
     print(i)
}
print(i)   //--5

When you define i without initializing it with a value, you need to specify its type.

The preceding can be rewritten by initializing the value of i and then omitting the initialization in the For loop:

Demo

//print from 0 to 4
var i = 0/*from   w w  w.  j  a  va2s.  c om*/
for ; i<5; i++ {   //the initialization part can be omitted
     print(i)
}
print(i)   //-5

You can count downwards-the following code snippet outputs the numbers from 5 to 1:

Demo

//print from 5 to 1
for var i = 5; i>0; i {
    print(i)/*from  www .  j a  va2s.  c o m*/
}

You can use the enumerate() function in Swift to iterate over an array.

The enumerate() function returns a tuple containing the index and the value of each element in the array:

Demo

let names =  ["M", "C", "A", "R"]
for (index, value) in enumerate(names) {
    print("names[\(index)] - \(value)")
}

Related Topic