Eric Hernandez
Eric Hernandez

Reputation: 11

Forin loop iteration error

For this section of code in REPL:

for counter in 0..<9 {

println("value at index \(counter) is \(numbersArray[counter])")

}

I receive numerous errors regarding placement of commas and semicolons even when following the example exactly how it shows in a book. I am new to swift and was doing fine up to this point, please help! Thanks!

Upvotes: 1

Views: 46

Answers (1)

Ian
Ian

Reputation: 12768

The likely culprit here is the count of the array. If you have an array of numbers:

let numbersArray = [1,2,3,4,5]

and you use the code:

for counter in 0..<9 {
    println("value at index \(counter) is \(numbersArray[counter])") // Error
}

You will receive an error because 9 is greater than the last object in the array. However, if you use the array's count as the last number in the for loop, the code works fine:

for counter in 0..<numbersArray.count {
    println("value at index \(counter) is \(numbersArray[counter])")
}

Also, if you're not in a playground, make sure this is contained within a method.

Upvotes: 1

Related Questions