嗨,大家好,所以我有理解這個代碼的問題:這不是一個var而不是let?
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)
不應該
let coordinatePoint = Point(x: xCoord, y: yCoord)
是一個變種,而不是一個讓?因爲它每次都在for循環中改變它的值?還是每次創建和銷燬?
謝謝!我懷疑可能是這種情況,但我並不完全確定。那麼在循環內創建的變量和常量會在每個循環完成後被銷燬? –
是的。循環的每次迭代都獨立於前一個循環,除了循環修改某些在自身之外聲明的內容。 –
@TomWayne,是的,這是它的意圖。儘管如此,不要在性能方面考慮它,因爲編譯器允許對其「聰明」。 – zneak