Swift - Statement For Loop

Introduction

Swift supports the traditional For loop in C, using the following syntax:

for  initialization ; condition ; increment/decrement {
    statement (s)
}

Unlike traditional C, in Swift you do not need to enclose the initialization ; condition ; increment/decrement block using a pair of parentheses ().

The following code snippet outputs the numbers from 0 to 4:

Demo

//print from 0 to 4
for var i = 0; i<5; i++ {
    print(i)/*from w w  w  .  j  av a2s.  c  om*/
}

The initializer must be a variable, not a constant, as its value needs to change during the iteration of the loop.

When the loop starts, i is initialized to 0, and its value is checked to see if it is less than five.

If it evaluates to true , the value of i is output.

If it evaluates to false , the For loop will end.

After all the statements in a For loop have been executed, the value of i is incremented by one.

It is then checked if it is less than five, and the loop continues if it evaluates to true .

Related Topics