Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Faraaz Khan
1,091 PointsPlease explain swift code.
Hello Everyone,
I am having trouble understanding this swift code. Basically, I don't know why we are writing the "[i]" in this piece of code: println(numbers[i])
Dont we just need to put "numbers" in the println()? Whats the point of the [i]?
Basically our task is to print the values in the "numbers" variable using a while method.
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var i = 0
while i < numbers.count {
println(numbers[i])
i += 1 }
1 Answer
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsI'm not sure which challenge you're on, but I'll take a crack at explaining this. Basically the variable i is short for index. We create it for the purpose of keeping track of how many times we've gone around the loop. So I've reworked your code a little bit:
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var i = 0
while i < numbers.count {
println(numbers[i])
i += 1
}
So what I did is create a loop. It says as long as i is less than the number of items in the "numbers" array, it will keep going around the loop. Then, inside the loop, we use the variable i for another purpose. We use that number to put iside of the square brackets, which will find us a certain index in the array. So the first time in the loop, i is 0 so it will go to numbers[0], then i gets incremented. Next time around the loop it's numbers[1], and then i gets incremented again. So what this code does is go through each number in the numbers array and print it out.
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsSo the short version of the explanation is that they want us to print out each thing one by one.
Faraaz Khan
1,091 PointsThanks for the answer! My understanding of this is so much better! Thank you so much.
Faraaz Khan
1,091 PointsFaraaz Khan
1,091 PointsCode:
while i < numbers.count {
println(numbers[i])
i += 1 }