在Swift中是否可以在for循环内定义一个常量?

huangapple go评论64阅读模式
英文:

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..&lt;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..&lt;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 variable 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 variable with this syntax where it's declared before the loop

var x : Double
for i in 0..&lt;n {
    x = start + delta * Double(i)
    result += [fn(x)]
}
return result

huangapple
  • 本文由 发表于 2023年5月25日 00:42:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76325757.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定