for loop in swift

A for loop in Swift is used to execute a block of code repeatedly. It has the following syntax:

for initialization; condition; increment/decrement {
    // Code to be executed
82 chars
4 lines

The initialization block is executed only once at the beginning of the loop. It can be used to declare and initialize any variables that will be used in the loop.

The condition block is evaluated at the beginning of each iteration. If it is true, the loop will continue to execute. If it is false, the loop will terminate and control will be passed to the next statement after the loop.

The increment/decrement block is executed at the end of each iteration. It can be used to increment or decrement variables used in the condition block.

Here is an example of using a for loop to iterate through an array of integers:

let numbers = [1, 2, 3, 4, 5]

for number in numbers {
75 chars
6 lines

In this example, the for loop iterates through each element in the numbers array and prints each number to the console.

Another example using a traditional for loop syntax:

for i in 0..<10 {
33 chars
4 lines

This for loop will run 10 times, with i taking on values from 0 to 9.

gistlibby LogSnag