OneBite.Dev - Coding blog in a bite size

Iterate Over An Array In Swift

Code snippet for how to Iterate Over An Array In Swift with sample and detail explanation

Iterating over an array in Swift is a common task that a developer needs to perform while writing code for Apple’s platforms. In this article, we’ll explore how you can iterate or loop through elements of an array using Swift programming language.

Code snippet: Iterating over an array in Swift

In Swift, we typically use the for-in loop to iterate over an array. Here is a short snippet illustrating this:

let array = ["Apple", "Banana", "Cherry"]

for item in array {
    print(item)
}

This code will output:

Apple
Banana
Cherry

Code Explanation: Iterating over an array in Swift

Let’s break down the code:

  • We start by creating an array of strings let array = ["Apple", "Banana", "Cherry"]. This will be the array that we will be looping over.

  • Next, we use the for-in pattern to iterate over each element in the array.

  • In the for-in loop, item is a temporary constant that Swift automatically sets to each item in the array, one after another.

  • The print(item) statement inside the loop prints out the value of item to the console.

When you run this code, you will see each element of the array printed out to the console in the order they appear in the array. This is because the for-in loop iterates over the array from beginning to end.

In conclusion, iterating over an array is quite straightforward in Swift using the for-in loop. This technique is not just limited to arrays but can be used with any collection, such as dictionaries or sets.

swift