Swift For Loop

Swift For Loop is used to execute a set of statements repeatedly for each item in a collection. Where collection could be a range, characters in a string, or items in an array.

In this tutorial, we will learn about Swift For Loop, its syntax and its usage with examples.

Syntax of Swift For Loop

Following is syntax of Swift For Loop in a program.

for index in var {
    // set of statements
 }

var could be a collection such as range of numbers, characters in a string or items in an array.

index is the element in var.

Example 1 – Swift For Loop – Over an Array

In this example, we will use for loop to iterate over an array of numbers.

main.swift

var salaries:[Int] = [500, 620, 410, 586]

for salary in salaries {
   print( "Salary paid to employee: \(salary)")
}

Output

$swift for_loop_example.swift
Salary paid to employee: 500
Salary paid to employee: 620
Salary paid to employee: 410
Salary paid to employee: 586

Example 2 – Swift For Loop – For each character in String

In this example, we will use for loop to iterate for each character in a string.

main.swift

var salaries:[Int] = [500, 620, 410, 586]

for salary in salaries {
   print( "Salary paid to employee: \(salary)")
}

Output

$swift for_loop_example.swift
character: t
character: u
character: t
character: o
character: r
character: i
character: a
character: l
character: k
character: a
character: r
character: t

Example 3 – Swift For Loop – Over a Range of Numbers

In this example, we will use For Loop to iterate over a range of numbers.

main.swift

var range = 8..<12

for item in range {
   print( "item: \(item)")
}

Output

$swift for_loop_example.swift
item: 8
item: 9
item: 10
item: 11

Conclusion

In this Swift Tutorial, we have learned about Swift For Loop with syntax and examples for different types of collections.