For loop in the programming language used to iterate a range of values of different types such as Arrays, Chars, collections, and dictionaries

Swift provides for in-loop syntax.

Swift for loop

Here is a syntax

for element in types [where condition]{
    // block of code
}

Each element is iterated with given Types and executed the block of code inside parenthesis. Code stops execution once all elements are iterated.

Where clause is optional.

Types can be of one of the following types

  • Sequence such as Arrays, Range of numbers of a string
  • Dictionary
  • Collections

Let’s see an examples

for in-loop iteration arrays with optional where clause

The array contains elements with index insertion order. The loop iterates each element and prints to the console.

let words = ["one", "two", "three", "four"]
for word in words {
    print(word)
}

Here is an example of a forin loop with where clause

let words = ["one", "two", "three", "four"]
for word in words where word != "four"{
    print(word)
}

for-in loop with iterate element and index in an array

Each Iterated object contains an index and element. the index always starts with zero and 1

let words = ["one", "two", "three", "four"]
for (index, word) in words.enumerated() {
     print("\(index) - \(word)")

}

Output:

0 - one
1 - two
2 - three
3 - four

for-in loop with a range of values

Here is an example for a range of values(using close range operator - …)

for the index in 5...10 {
    print("\(index)")
}

Swift for loop dictionary with index

The dictionary contains keys and values. We can iterate the dictionary using an iteration of an object Each object contains keys and values in a for-in loop.

This is an example of an iteration of a dictionary in swift

let employee : [String : Any] = ["id": 1, "name": "john", "salary": 4000]
for (key, value) in employee {
    print("\(key)-  \(value)")
}

Output:

salary-  4000
id-  1
name-  john