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".
SPONSORED Fernando's book will guide you in fixing bugs in three real, open-source, downloadable apps from the App Store. Learn applied programming fundamentals by refactoring real code from published apps. Hacking with Swift readers get a $10 discount!
Sponsor Hacking with Swift and reach the world's largest Swift community!
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.