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

iOS

Looping over ranges code challenge task 2 question.

I am trying to figure out how to appended the multiples of 6 from the constant multiple into the array.

var results: [Int] = []

for multiplier in 0...10 { results[multiplier] = (multiplier * 6) }

I thought this would work, but I am not sure why its not working. Help would be greatly appreciated.

2 Answers

At a glance, you're not appending the results to the list; you're trying to replace a nonexistent index in an empty list with each multiple, instead. You're also starting your list at 0 instead of 1.

var results: [Int] = []
for multiplier in 1...10 {
    results.append(multiplier * 6)
}

Hope this helps!

Thank you! I put 0...10 so that my array would start at index 0 . So when you append it will automatically go to the next index. Instead of modifying the same index multiple times.

Actually, your original code would work if you first initialized the list with 10 blank numbers, started the multiplier at 1, then subtracted 1 from your multiplier index; that way, you aren't trying to access a nonexistent index, your index would start at 0, and you'd still have the 1...10 that the multiplier is looking for in this challenge.

var results: [Int] = [0,0,0,0,0,0,0,0,0,0]

for multiplier in 1...10 {
    results[multiplier-1] = (multiplier * 6) 
}

Awesome thank you!

Thank you for explaining it, very helpful.