OneBite.Dev - Coding blog in a bite size

Loop Array In Swift

Code snippet for how to Loop Array In Swift with sample and detail explanation

Looping over an array in Swift is a basic yet essential concept in iOS development and Swift programming. This article provides a simple tutorial on how to iterate or loop through an array in Swift, complete with an easy-to-understand example.

Code Snippet: Loop Array in Swift

Here’s a simple code snippet illustrating how to loop an array in Swift:

let swiftArray = ["Swift", "iOS", "Development", "Array", "Loop"]

for item in swiftArray {
    print(item)
}

Code Explanation for Loop Array in Swift

In this tutorial, we will take a step-by-up approach to understanding how the above code works.

  1. First, we create an array swiftArray that holds five string elements - “Swift”, “iOS”, “Development”, “Array”, “Loop”.
let swiftArray = ["Swift", "iOS", "Development", "Array", "Loop"]
  1. The for-in loop is then used to iterate through each element in the array. In Swift, the for-in is the most common way to loop through an array. The item variable represents the current element in the array during each iteration through the loop.
for item in swiftArray {
  1. Inside the loop, we have a simple print statement that will print each element of the array to the console. This block of code executes for each iteration of the loop.
    print(item)
}

As the loop iterates over each item in the swiftArray, it will print the item. So, the result will be “Swift”, “iOS”, “Development”, “Array”, “Loop” printed as separate lines in the console. After the last element of the array, the loop ends and no further iterations occur.

This demonstrates the fundamental steps to loop over an array in Swift. Looping over arrays is a fundamental part of most programming languages, and Swift makes this process intuitive and efficient.

swift