swift Array forEach() Function



The forEach() function is a pre-defined function in Swift. It is used to call a closure on each element of the given sequence. It is like a for-in loop but in a more optimized form. It does not use any break or continue statements to exit from the current call. It uses a return statement in the closure body to exit from the current call. It does not skip any subsequent call

For example, we have an array = [4, 9, 2]. Now using the array.forEach{x in print(x)} function we will display the given array:

4
9
2

Syntax

Following is the syntax of the forEach() function −

func forEach(_mClosure:(Self.Element) throws -> Void) rethrows

Parameters

This function takes a closure. Here mClosure represents the closure which takes each element of the given array as a parameter.

Now we will discuss the use of the forEach() function with the help of the following examples:

Example 1

Swift program to iterate through each element of the given arrays and print them using the forEach() function.

import Foundation

// Input array 1
let numbers = [23, 56, 29, 44, 34, 98, 56, 77]

print("Numbers:")

// Iterating through each element and printing them using the forEach() function
numbers.forEach { num in
    print(num)
}

// Input array 2
let string = ["Car", "Speed Boat", "Bike", "Truck"]

print("Strings:")

// Iterating through each element and printing them using the forEach() function
string.forEach { str in
    print(str)
}

Output

Numbers:
23
56
29
44
34
98
56
77
Strings:
Car
Speed Boat
Bike
Truck

Example 2

Swift program to calculate the square of each element present in the given array using the forEach() function.

import Foundation

// Array of integer type
let nums = [11, 33, 66, 88, 66, 22]

// Empty array to store square of numbers
var sqNums: [Int] = []

// Iterate through each element and find their square 
nums.forEach { x in
    sqNums.append(x * x)
}

// Display result
print("Array:", nums)
print("Squared Numbers: \(sqNums)")

Output

Array: [11, 33, 66, 88, 66, 22]
Squared Numbers: [121, 1089, 4356, 7744, 4356, 484]

Example 3

Swift program to find even numbers from the given array and then display them using the forEach() function.

import Foundation

// Array of integer type
let nums = [11, 33, 16, 88, 66, 22, 12, 8, 10]

print("Even Numbers:")

// Iterate through each element and display only even elements
// Using forEach() function
nums.forEach { elements in
    if elements % 2 == 0 {
        print(elements)
    }
}

Output

Even Numbers:
16
88
66
22
12
8
10

Example 4

Swift program to find and display the index of the given element using the forEach() function.

import Foundation

// Input Array of string type
let veggies = ["BeetRoot", "Potato", "Tomato", "Peas"]

// Element we want to find
let findVeggies = "Potato"

var found = false

// Finding the element and index 
veggies.enumerated().forEach { indexValue, element in
    if element == findVeggies {
        print("Index of \(findVeggies): \(indexValue)")
        found = true
    }
}

// If the element is not found
if !found {
    print("Given veggies not found")
}

Output

Index of Potato: 1
Advertisements