Loop Through Array Elements in Swift

Lets’ create an Array with three elements first.

var myArray = ["Swift", "Objective-C", "PHP"]

Now we can loop through all elements in Array

for arrayElement in myArray {
 print(arrayElement) 
}

Loop through an array of elements and print out element index as well as element value.

for (index, element) in myArray.enumerated() {
    print("Element index: \(index). Element value \(element)")
}

Print all array elements using the forEach loop.

myArray.forEach {
    print("Element value \($0)")
}

Loop through an array of elements starting from a specific array index.

for i in 0 ..< myArray.count {
    print("Element indexL \(i). Element value: \(myArray[i])")
}

Loop through all elements in an array using the “for loop”.

for i in myArray.indices {
    print("Element index: \(i). Element value: \(myArray[i])")
}

Loop through array elements backward using the reversed() function.

for i in myArray.indices.reversed() {
    print("Element index: \(i). Element value: \(myArray[i])")
}

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 *

Free Video Lessons

Enter your email and stay on top of things,

Subscribe!