英文:
Is defining a constant within a for-loop possible in Swift?
问题
在书中初学Swift时,我遇到了以下的代码:
for i in 0..<n {
let x = start + delta * Double(i)
result += [fn(x)]
}
return result
让我困惑的是,x似乎被定义为一个常量,但在for循环内部,这应该是不可能的,因为它会改变其值。
我预期的代码应该是:
for i in 0..<n {
var x = start + delta * Double(i)
result += [fn(x)]
}
return result
英文:
Just beginning to learn Swift and stumbled across the following code in a book:
for i in 0..<n {
let x = start + delta * Double(i)
result += [fn(x)]
}
return result
What puzzles me is, that x seems to be defined as a constant, but within a for loop, which should not be possible as it changes its value.
I was expecting something like:
for i in 0..<n {
var x = start + delta * Double(i)
result += [fn(x)]
}
return result
答案1
得分: 4
It does not change the value, the local constant is (re)created in each iteration and thrown away in the closing brace line.
它不改变值,局部常量在每次迭代中都会被重新创建,并在结束括号行被丢弃。
It changes the value, therefore it must be a var
iable with this syntax where it's declared before the loop.
它改变了值,因此必须使用此语法声明为 var
变量,并且在循环之前声明,如下所示:
var x : Double
for i in 0..<n {
x = start + delta * Double(i)
result += [fn(x)]
}
return result
英文:
> … as it changes its value.
It does not change the value, the local constant is (re)created in each iteration and thrown away in the closing brace line.
It changes the value therefore it must be a var
iable with this syntax where it's declared before the loop
var x : Double
for i in 0..<n {
x = start + delta * Double(i)
result += [fn(x)]
}
return result
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论