Swift: 5 Ways to Iterate over an Array

Updated: May 4, 2023 By: Khue Post a comment

Array iteration is the process of traversing through the elements of an array one by one, usually to perform some operation on each element. Iterating through arrays is a common task in Swift as well as in other programming languages, as it allows developers to process and manipulate data stored in arrays effectively.

This practical, code-centric article will walk you through a couple of different ways to iterate over an array in Swift. Without any further ado, let’s get started.

Using a for-in loop

The simplest and most common method of iterating through arrays in Swift is by using the for-in loop. The for-in loop iterates through all the elements in an array in sequential order, allowing developers to perform operations on each element. This approach doesn’t involve using an index variable.

Example:

let words = ["Sling", "Academy", "Swift", "Programming", "iOS"]
for word in words {
    print(word)
}

Output:

Sling
Academy
Swift
Programming
iOS

Using the enumerated() method

Sometimes, you may need to iterate through an array while also keeping track of the index of each element. Swift provides the enumerated() method for this purpose, which returns a sequence of tuples containing the index and value of each element in the array.

Example:

let animals = ["cat", "dog", "elephant", "turtle"]

for (index, animal) in animals.enumerated() {
    print("Animal at index \(index): \(animal)")
}

Output:

Animal at index 0: cat
Animal at index 1: dog
Animal at index 2: elephant
Animal at index 3: turtle

Using the forEach() method

You can use the forEach() method to iterate over the array with a closure that takes each element as a parameter. This method is similar to the for-in loop, but it allows you to use trailing closure syntax and shorthand arguments

Example:

let myArray = ["welcome", "to", "sling", "academy"]
myArray.forEach{element in 
    print(element)
}

Output:

welcome
to
sling
academy

Using a While Loop

You can use a while loop to iterate over the array with an index variable that you increment manually. You need to check that the index is within the bounds of the array before accessing each element.

Example:

let myArray = ["welcome", "to", "sling", "academy"]
var i = 0
while i < myArray.count {
    print("The element at index \(i) is '\(myArray[i])'")
    i += 1
}

Output:

The element at index 0 is 'welcome'
The element at index 1 is 'to'
The element at index 2 is 'sling'
The element at index 3 is 'academy'

Using high-order functions

Swift provides several powerful higher-order functions for working with arrays, including map(), filter(), and reduce(). These functions enable developers to perform complex operations on arrays in a more functional and expressive manner.

map() is used to transform an array’s elements into a new array of a different type. It accepts a closure as an argument, which is applied to each element in the array.

filter() is used to create a new array containing only the elements that satisfy a given condition. It takes a closure as an argument, which is used to determine if an element should be included in the resulting array.

reduce() is used to combine all the elements of an array into a single value, using a specified closure.

In the following example, the filter() function creates a new array containing only the even numbers. The map() function then squares each even number, and finally, the reduce() function adds up the squared even numbers to compute the sum.

let numbers = [1, 2, 3, 4, 5]

let sumOfSquaresOfEvenNumbers = numbers
    .filter { $0 % 2 == 0 }
    .map { $0 * $0 }
    .reduce(0, +)

print(sumOfSquaresOfEvenNumbers)
// Output: 20

You can find more details about mentioned high-order functions in these articles:

Performance

When working with arrays in Swift, it’s essential to consider the performance implications of different iteration techniques. While some methods may be more concise or expressive, they may not always be the most performant option.

For example, using higher-order functions like map(), filter(), and reduce() can sometimes result in slower performance compared to using a simple for-in loop, as these functions may create intermediate arrays or involve additional function calls.

However, this performance difference is often negligible for small arrays and may not be a significant concern in most cases. It’s crucial to measure and profile your code to determine the most appropriate technique based on your specific performance requirements.

Conclusion

In this article, we’ve explored various techniques for iterating through arrays in Swift, including basic and advanced methods, along with code examples to demonstrate their usage. By understanding these techniques and employing best practices, you’ll be well-equipped to write efficient, readable, and performant code when working with arrays in Swift. So, get out there and start iterating through arrays like a pro!