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.
Array iteration and enumerated in 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.
let emptyArray: [String] = [] for item in emptyArray { print(item) } // No output because the array is empty
let singleItemArray = ["only"] for (index, item) in singleItemArray.enumerated() { print("Index: \(index), Item: \(item)") }
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)") } }
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.
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)") }
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.
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.