- Swift - Home
- Swift - Overview
- Swift - Environment
- Swift - Basic Syntax
- Swift - Variables
- Swift - Constants
- Swift - Literals
- Swift - Comments
- Swift Operators
- Swift - Operators
- Swift - Arithmetic Operators
- Swift - Comparison Operators
- Swift - Logical Operators
- Swift - Assignment Operators
- Swift - Bitwise Operators
- Swift - Misc Operators
- Swift Advanced Operators
- Swift - Operator Overloading
- Swift - Arithmetic Overflow Operators
- Swift - Identity Operators
- Swift - Range Operators
- Swift Data Types
- Swift - Data Types
- Swift - Integers
- Swift - Floating-Point Numbers
- Swift - Double
- Swift - Boolean
- Swift - Strings
- Swift - Characters
- Swift - Type Aliases
- Swift - Optionals
- Swift - Tuples
- Swift - Assertions and Precondition
- Swift Control Flow
- Swift - Decision Making
- Swift - if statement
- Swift - if...else if...else Statement
- Swift - if-else Statement
- Swift - nested if statements
- Swift - switch statement
- Swift - Loops
- Swift - for in loop
- Swift - While loop
- Swift - repeat...while loop
- Swift - continue statement
- Swift - break statement
- Swift - fall through statement
- Swift Collections
- Swift - Arrays
- Swift - Sets
- Swift - Dictionaries
- Swift Functions
- Swift - Functions
- Swift - Nested Functions
- Swift - Function Overloading
- Swift - Recursion
- Swift - Higher-Order Functions
- Swift Closures
- Swift - Closures
- Swift-Escaping and Non-escaping closure
- Swift - Auto Closures
- Swift OOps
- Swift - Enumerations
- Swift - Structures
- Swift - Classes
- Swift - Properties
- Swift - Methods
- Swift - Subscripts
- Swift - Inheritance
- Swift-Overriding
- Swift - Initialization
- Swift - Deinitialization
- Swift Advanced
- Swift - ARC Overview
- Swift - Optional Chaining
- Swift - Error handling
- Swift - Concurrency
- Swift - Type Casting
- Swift - Nested Types
- Swift - Extensions
- Swift - Protocols
- Swift - Generics
- Swift - Access Control
- Swift - Function vs Method
- Swift - SwiftyJSON
- Swift - Singleton class
- Swift Random Numbers
- Swift Opaque and Boxed Type
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