Doug Smith
Doug Smith

Reputation: 29314

When iterating through an array in Swift, is there a reference the index/iteration of the loop?

Say I have the following code:

var array = [1, 5, 6, 2, 7, 4]

for item in array {
    println(index)
}

Is there a way to access what iteration the loop is on within the loop's body? (i.e.: 0, 1, 2, 3...)

Upvotes: 1

Views: 866

Answers (2)

Christian Dietrich
Christian Dietrich

Reputation: 11868

var array = [1, 5, 6, 2, 7, 4]

for (index,item) in enumerate(array) {
    println("\(index): \(item)")
}

Upvotes: 11

Millie Smith
Millie Smith

Reputation: 4604

You can create a count variable. Other than that, you need to use a regular for loop.

Upvotes: 0

Related Questions