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 Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!
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.