Home »
Swift »
Swift Programs
Swift program to access array elements using forEach() function
Here, we are going to learn how to access array elements using forEach() function in Swift programming language?
Submitted by Nidhi, on June 17, 2021
Problem Solution:
Here, we will create an array of integers and access each element from the array using the forEach() function, and print the array elements on the console screen.
Program/Source Code:
The source code to access array elements using the forEach() function is given below. The given program is compiled and executed successfully.
// Swift program to access array elements using
// forEach() function
import Swift
var arr:[Int] = [12,10,25,20,50]
print("Array elements: ")
arr.forEach {
print($0)
}
Output:
Array elements:
12
10
25
20
50
...Program finished with exit code 0
Press ENTER to exit console.
Explanation:
In the above program, we imported a package Swift to use the print() function using the below statement,
import Swift;
Here, we created an integer array arr. Then we used the forEach() function to access array elements and printed them on the console screen.
Swift Array Programs »