Swift version: 5.6
There several ways to loop through an array in Swift, but using the enumerated()
method is one of my favorites because it iterates over each of the items while also telling you the items's position in the array.
Here's an example:
let array = ["Apples", "Peaches", "Plums"]
for (index, item) in array.enumerated() {
print("Found \(item) at position \(index)")
}
That will print "Found Apples at position 0", "Found Peaches at position 1", and "Found Plums at position 2".
SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Available from iOS 7.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.