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

question about this for in loop and how it works

in this piece of code i need some help..

func surroundingPoints(withRange range: Int = 1) -> [Point] {

    var results: [Point] = []
    for xCoord in (x-range)...(x+range) {
        for yCoord in (y-range)...y+range {
            let coordinatePoint = Point(x: xCoord, y: yCoord)
            results.append(coordinatePoint)

// i want to know in what order the for loops are appended to the array so i know exactly whats going on..

What Pasan is saying is the first xCoord x-1 iterates thru the next for in loop so example... [x-1,y-1, x-1,y-0, x-1,y+1, x-0,y-1, x-0,y-0, x-0,y+1 and so on...] i just want to know why if this is the case it dosent just go [x-1,y-1, x-0,y-0, x+1, y+1 and so on..]

hope you understand what I'm asking, thanks

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

I think I understand what you're asking. And nested for loops can take a bit to understand! So no worries :smiley: What he's saying here is for every x coordinate do every y coordinate. So we're staring with the x-1 and then listing every possible y coordinate. So we won't move on to the next x coordinate until all the y coordinates are listed out. Then when those are done we move onto the next x coordinate and then list every possible y coordinate with that one. Hope this makes sense! :sparkles: