0
0
Swiftprogramming~5 mins

Array iteration and enumerated in Swift

Choose your learning style9 modes available
Introduction

We use array iteration to look at each item in a list one by one. Enumerated helps us see both the item and its position in the list.

When you want to print all items in a shopping list.
When you need to check each student's score in a class.
When you want to find the position of a specific item while going through a list.
When you want to number items as you show them on screen.
Syntax
Swift
let array = ["apple", "banana", "cherry"]

// Simple iteration
for item in array {
    print(item)
}

// Using enumerated to get index and item
for (index, item) in array.enumerated() {
    print("Item \(index): \(item)")
}

The for-in loop goes through each item in the array.

The enumerated() method gives both the position (index) and the item.

Examples
This shows what happens if the array has no items. The loop does not run.
Swift
let emptyArray: [String] = []
for item in emptyArray {
    print(item)
}
// No output because the array is empty
When the array has one item, enumerated still works and shows index 0.
Swift
let singleItemArray = ["only"]
for (index, item) in singleItemArray.enumerated() {
    print("Index: \(index), Item: \(item)")
}
This example shows how to check if the item is first, last, or in the middle using the index.
Swift
let fruits = ["apple", "banana", "cherry"]
for (index, item) in fruits.enumerated() {
    if index == 0 {
        print("First fruit: \(item)")
    } else if index == fruits.count - 1 {
        print("Last fruit: \(item)")
    } else {
        print("Middle fruit: \(item)")
    }
}
Sample Program

This program shows a list of colors. It first prints the whole list. Then it prints each color one by one. Finally, it prints each color with its number starting from 1.

Swift
import Foundation

let colors = ["Red", "Green", "Blue"]

print("Colors before iteration:")
print(colors)

print("\nIterating over colors:")
for color in colors {
    print(color)
}

print("\nIterating with index and color:")
for (index, color) in colors.enumerated() {
    print("Color number \(index + 1): \(color)")
}
OutputSuccess
Important Notes

Time complexity is O(n) because we look at each item once.

Space complexity is O(1) extra space since we only use variables for the loop.

A common mistake is forgetting that array indexes start at 0, so numbering might be off by one if not adjusted.

Use simple iteration when you only need items. Use enumerated when you also need the position of each item.

Summary

Array iteration lets you visit each item in a list one by one.

Enumerated gives you both the item and its position (index) in the list.

Remember indexes start at 0, so add 1 if you want to show counting from 1.