Loop Through Array Elements in Swift

Lets’ create an Array with three elements first.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var myArray = ["Swift", "Objective-C", "PHP"]
var myArray = ["Swift", "Objective-C", "PHP"]
var myArray = ["Swift", "Objective-C", "PHP"]

Now we can loop through all elements in Array

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
for arrayElement in myArray {
print(arrayElement)
}
for arrayElement in myArray { print(arrayElement) }
for arrayElement in myArray {
 print(arrayElement) 
}

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
for (index, element) in myArray.enumerated() {
print("Element index: \(index). Element value \(element)")
}
for (index, element) in myArray.enumerated() { print("Element index: \(index). Element value \(element)") }
for (index, element) in myArray.enumerated() {
    print("Element index: \(index). Element value \(element)")
}

Print all array elements using the forEach loop.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
myArray.forEach {
print("Element value \($0)")
}
myArray.forEach { print("Element value \($0)") }
myArray.forEach {
    print("Element value \($0)")
}

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
for i in 0 ..< myArray.count {
print("Element indexL \(i). Element value: \(myArray[i])")
}
for i in 0 ..< myArray.count { print("Element indexL \(i). Element value: \(myArray[i])") }
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”.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
for i in myArray.indices {
print("Element index: \(i). Element value: \(myArray[i])")
}
for i in myArray.indices { print("Element index: \(i). Element value: \(myArray[i])") }
for i in myArray.indices {
    print("Element index: \(i). Element value: \(myArray[i])")
}

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
for i in myArray.indices.reversed() {
print("Element index: \(i). Element value: \(myArray[i])")
}
for i in myArray.indices.reversed() { print("Element index: \(i). Element value: \(myArray[i])") }
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 *