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 trialLeslie Wells
1,215 PointsWhere is 2,2?
Where in this method are we stating the starting Point of 2,2, in order for it to iterate the range for us?
It is going through the range correctly but where did we tell it where our point was, I'm a bit confused on that part.
2 Answers
Oliver Duncan
16,642 PointsThe method getSurroundingPoints() is an instance method of the struct Point. This means that you can only call this function on an instance of Point, and it will act on the properties of whatever instance of Point you call it on. I'll rewrite using self to make it a little more clear.
struct Point {
var x: Int
var y: Int
func surroundingPoints(withRange range: Int) -> [Point] {
var result = [Point]()
for xCoord in (self.x - range)...(self.x + range) { // self.x refers to the stored property, x, of the instance of this struct
for yCoord in (self.y - range)...(self.y + range) { // self.y refers to the stored property, y, of the instance this struct
result.append(Point(x: xCoord, y: yCoord))
}
}
return result
}
}
let somePoint = Point(x: 2, y: 2)
somePoint.surroundingPoints(withRange: 1) // [Point(x: 1, y: 1), Point(x: 1, y: 2), Point(x: 1, y: 3), Point(x: 2, y: 1), Point(x: 2, y: 2), Point(x: 2, y: 3), Point(x: 3, y: 1), Point(x: 3, y: 2), Point(x: 3, y: 3)]
let anotherPoint = Point(x:3, y: 3)
anotherPoint.surroundingPoints(withRange: 1) // [Point(x: 2, y: 2), Point(x: 2, y: 3), Point(x: 2, y: 4), Point(x: 3, y: 2), Point(x: 3, y: 3), Point(x: 3, y: 4), Point(x: 4, y: 2), Point(x: 4, y: 3), Point(x: 4, y: 4)]
Leslie Wells
1,215 PointsOk I understand now. It doesn't know where our point is until we call an instance. Is that correct??
Oliver Duncan
16,642 PointsYeah. You create an instance of Point with its location, then use instance methods to get even more information out of the data.
Juan Davin
1,074 PointsJuan Davin
1,074 PointsHi, you can do all this without using the struct method right?(using parameters to input the value of x and y) why would one use struct then?