forEach
The forEach function is used to perform an action on each element of a sequence. Unlike the map function, which returns a new sequence of transformed elements, forEach does not return a value. Instead, it simply performs the specified action on each element of the sequence.
Syntax:
Here is the basic syntax for the forEach function:
sequence.forEach(perform)
The perform closure is a function that takes an element of the sequence as its input and performs an action on that element.
Example 1:
Here is the below example we are using the forEach function to print each element of an array of strings:
Swift
// Swift program to use forEach function let words = [ "apple" , "banana" , "cherry" ] // Using forEach() function to print all the // elements of the given array words.forEach { print ($0) } |
Output:
apple banana cherry
In this example, the forEach function applies the closure { print($0) } to each element in the words array, printing each element to the console.
You can also use the forEach function to perform more complex actions on each element of a sequence.
Example 2:
In the following example, we are using forEach to increment a counter for each even element in an array.
Swift
// Swift program to use forEach() function var counter = 0 let numbers = [1, 2, 3, 4, 5] // Counting even numbers numbers.forEach { if $0 % 2 == 0 { counter += 1 } } print (counter) |
Output:
2
In this example, the forEach function applies the closure { if $0 % 2 == 0 { counter += 1 } } to each element in the numbers array, incrementing the counter variable for each even element.
Higher-Order Functions in Swift
Higher-order functions are functions that take other functions as arguments or return functions as their output. These functions are an important aspect of functional programming, which is a programming paradigm that focuses on the use of functions to model computation. Higher-order functions enable developers to abstract common patterns of function applications and make code more concise and reusable.
In Swift, higher-order functions are a powerful tool for manipulating and transforming collections of data. Swift provides several higher-order functions as part of its standard library, including map, filter, reduce, and sorted. In this article, we will explore these functions in detail, along with some examples of how they can be used.
Contact Us