Reputation: 57
Hi guys so I have an issue with understanding this code:
struct Point {
// Passing in values
// X = 1
let x: Int
// y = 1
let y: Int
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)
print(coordinatePoint)
}
}
return results
}
}
// Creating an instance and assigning to a constant called coordinatePoint
let coordinatePoint = Point(x: 1, y: 1)
print(coordinatePoint)
// Calling the function inside Point instance
coordinatePoint.surroundingPoints()
print(coordinatePoint)
Shouldn't
let coordinatePoint = Point(x: xCoord, y: yCoord)
be a var instead of a let? As it's changing it's value each time around the for loop? or is it created and destroyed each time?
Upvotes: 2
Views: 109
Reputation: 2002
No. coordinatePoint
is created and then destroyed once for each iteration of the for loop. (Its scope is limited to the for loop it is declared inside.) This is just like how a local variable in a function will be created and destroyed once each time you invoke the function.
If you wanted to use a var instead of a let, then you would declare it outside the scope of the for loop as follows:
func surroundingPoints(withRange range: Int = 1) -> [Point] {
var results: [Point] = []
var coordinatePoint: Point
for xCoord in (x-range)...(x+range) {
for yCoord in (y-range)...(y+range) {
coordinatePoint = Point(x: xCoord, y: yCoord)
results.append(coordinatePoint)
print(coordinatePoint)
}
}
return results
}
Now coordinatePoint
is created only once per invocation of the method. There's no particular advantage to doing so however, and using a let is probably preferable from a stylistic point of view.
Upvotes: 1
Reputation: 11
No - coordinatePoint inside the loop is locally scoped to that inner loop. It ceases to exist directly after the print and is recreated on the next iteration.
Upvotes: 1
Reputation: 4337
let
or var
, it depends on scope of you will use it. If you want change value after use in the same scope, you have to use var
. If not you will use let
. When you run this scope it will create and end scope it will be destroyed.
Upvotes: 0
Reputation: 3349
The variable is created and destroyed each time, so either would work just fine. It would be a different story if you had defined coordinatePoint
above the for loop. In this case, you would have to use var
.
Upvotes: 4