Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Swift 2.0 Collections and Control Flow Control Flow With Loops For In Loops

Multiplier quiz

Inside the body of the loop, we're going to use the multiplier to get the multiple of 6. For example, if the multiplier is 1, then the multiple is 1 times 6, which is equal to 6.

Once you have a value, append it to the results array. This way once the for loop has iterated over the entire range, the array will contain the first 10 multiples of 6.

2 Answers

Nathan Tallack
Nathan Tallack
22,158 Points

This challenge is trying to teach you how to use a for loop and append the results of an operation within that loop to an array you defined outside of the loop.

Consider the following code.

var results: [Int] = []    // Create array to use in loop.

let multiplier = 6    // Multiplier to use in loop.

for i in 1...10 {    // Loop through numbers 1 to 10 inclusive.
    results.append(i*multiplier)  // Append result of num*multiplier to results array.
}

Key takeaways are:

  • We are using 1...10 to create an iterable array of numbers 1 through 10 inclusive for the for loop to iterate over.
  • We are setting the value i to the next number in the array each time through the for loop.
  • We are multiplying i with the multiplier (6 in this case) each time through the for loop.
  • We are adding the results of i * 6 to the results array each time through the for loop.

Hey Nathan, thanks a lot. I wasn't getting it.

Nathan Tallack
Nathan Tallack
22,158 Points

No problem! That's what makes learning here so wonderful. If there is something you need a little help with there are plenty of people on the forums to help out. :)

Chung Teng Chiang
Chung Teng Chiang
4,401 Points

I still can't pass the challenge... Here is my code:

var results: [Int] = [1,2,3,4,5,6,7,8,9,10]

for multiplier in 1...10 { let multiple = multiplier * 6 results.append(multiplier) }

what's the problem?

Nathan Tallack
Nathan Tallack
22,158 Points

The problem is that you are pre-populating your results array with the numbers 1 thru 10, which means you will end up with them in there twice when you run your for loop.

Try declaring the results array as an empty array and see if that helps. :)