Swift program to demonstrate the use of the enumerated() function

Here, we are going to demonstrate the use of the enumerated() function in Swift programming language.
Submitted by Nidhi, on June 17, 2021

Problem Solution:

Here, we will create an array of integer elements. Then we will use the enumerated() function to access array elements. The enumerated() function iterates over each of the items while also telling you the items' position in the array.

Program/Source Code:

The source code to demonstrate the use of the enumerated() function is given below. The given program is compiled and executed successfully.

// Swift program to demonstrate the
// use of enumerated() function

import Swift

var arr:[Int] = [12,10,25,20,50]

for (index, item) in arr.enumerated() {
    print("Item \(item) at position \(index)")
}

Output:

Item 12 at position 0
Item 10 at position 1
Item 25 at position 2
Item 20 at position 3
Item 50 at position 4

...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 array arr that contains 5 integer elements. Then we accessed array elements using the enumerated() function and printed the items with an index on the console screen.

Swift Array Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.