Loop Over Array of Elements with Index

In this tutorial, you will learn how to use index along with element in Array loop. When iterating over an array, if you need the index for each element along with its value, you can use the enumerated() method to iterate over the array

Create an Array

First, let’s create an array with some elements.

// Create an Array with three elements
var myArray = ["Swift", "Objective-C", "PHP"]

Loop Over Array

Now that we have an array with three elements, we can iterate through its elements and print out the element index and value.

// Iterate over Array elements. Display element and it's index
for (index, element) in myArray.enumerated() {
    print("Element \(element) is at index \(index)")
}

For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.


Leave a Reply

Your email address will not be published. Required fields are marked *