If constants are immutable, why can I reassign them using let?

时间:2015-09-01 21:51:13

标签: ios swift constants immutability

From the Apple docs "Learn the Essentials of Swift"

A constant is a value that stays the same after it’s declared the first time, while a variable is a value that can change. A constant is referred to as immutable, meaning that it can’t be changed, and a variable is mutable. If you know that a value won’t need to be changed in your code, declare it as a constant instead of a variable.

Yet in the REPL, I can do this:

 14> let favoriteNumber = 4
favoriteNumber: Int = 4
 15> let favoriteNumber = 5
favoriteNumber: Int = 5

I am clearly missing something: does this discrepancy have to do with the compiler or runtime, or is it something else?

enter image description here

3 个答案:

答案 0 :(得分:5)

You can do things in the REPL that you can't do in normal code.

You can't re-assign constants in a playground or in compiled code.

I am not sure if this is a special convenience offered in the REPL, or a bug.

答案 1 :(得分:3)

I can see how this gives the impression you are changing the value of a constant, but in actuality you aren't changing the value of favoriteNumber. What is happening is you are declaring a new constant with the same identifier as the previous declaration. In essence this hides the first declaration and it is if only the second favoriteNumber exists. If you try the following:

let favoriteNumber = 4
favoriteNumber = 5

You will see that you are not allowed to change the value of a constant.

It would probably be helpful if the REPL produced a warning that you redeclared an existing constant or variable.

答案 2 :(得分:0)

这是不允许的

不允许重新分配常量。
从Swift 5.2开始,建议您不要重新声明它们(或至少在相同范围内对它们进行无效的重新声明):

let this = true
let this = false
// Compiler Error: Invalid redeclaration if 'this'

在REPL中,您可能被允许重新声明值。由于以下原因,我很确定:


但是秘密地是

显然,您不需要REPL即可重新声明 值。

我偶然发现您可以执行此操作,它将编译:

let this = true
guard case let this = 100 else {}
print(this) // 1

您甚至可以将值重新声明为其他类型,这很酷。

由于我们只有hid[ing] the first declaration,因此可以。