Swift – Array forEach()

Swift Array forEach() can be used to execute a block of code for each element in this Array.

The following is a quick code snippet to use forEach() method on an Array array.

array.forEach { element in
    //code
}

Examples

In the following program, we take an array of numbers, and print each of them to console using Array.forEach() method.

main.swift

let nums = [2, 4, 6, 8]

nums.forEach { x in
    print(x)
}

Output

2
4
6
8
Program ended with exit code: 0

Now, let us take an array of strings, iterate over elements of this array using Array.forEach() method and print their lengths to console.

main.swift

let names = ["apple", "banana", "fig"]

names.forEach { x in
    let length = x.count
    print("\(x) - \(length)")
}

Output

apple - 5
banana - 6
fig - 3
Program ended with exit code: 0
ADVERTISEMENT

Conclusion

In this Swift Tutorial, we learned how to iterate over the elements of an array, and execute a piece of code for each element, using Array.forEach() method, in Swift programming.