如果常量是不可变的,为什么我可以使用 let 重新分配它们?
If constants are immutable, why can I reassign them using let?
来自 Apple 文档“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.
然而在 REPL 中,我可以这样做:
14> let favoriteNumber = 4
favoriteNumber: Int = 4
15> let favoriteNumber = 5
favoriteNumber: Int = 5
我显然遗漏了一些东西:这种差异是否与编译器或运行时有关,还是其他原因?
您可以在 REPL 中完成在普通代码中无法完成的事情。
您不能在 playground 或编译代码中重新分配常量。
我不确定这是 REPL 中提供的特殊便利,还是一个错误。
我明白这给人的印象是您正在更改常量的值,但实际上您并没有更改 favoriteNumber 的值。发生的事情是您正在声明一个新常量,该常量具有与先前声明相同的标识符。本质上,这隐藏了第一个声明,并且只有第二个 favoriteNumber 存在。如果您尝试以下操作:
let favoriteNumber = 4
favoriteNumber = 5
您会看到不允许更改常量的值。
如果 REPL 发出警告,提示您重新声明了现有常量或变量,这可能会有所帮助。
这是不允许的
不允许重新分配常量。
从 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
很酷,您甚至可以将一个值重新声明为不同的类型。
因为我们只有 ,这是允许的。
来自 Apple 文档“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.
然而在 REPL 中,我可以这样做:
14> let favoriteNumber = 4
favoriteNumber: Int = 4
15> let favoriteNumber = 5
favoriteNumber: Int = 5
我显然遗漏了一些东西:这种差异是否与编译器或运行时有关,还是其他原因?
您可以在 REPL 中完成在普通代码中无法完成的事情。
您不能在 playground 或编译代码中重新分配常量。
我不确定这是 REPL 中提供的特殊便利,还是一个错误。
我明白这给人的印象是您正在更改常量的值,但实际上您并没有更改 favoriteNumber 的值。发生的事情是您正在声明一个新常量,该常量具有与先前声明相同的标识符。本质上,这隐藏了第一个声明,并且只有第二个 favoriteNumber 存在。如果您尝试以下操作:
let favoriteNumber = 4
favoriteNumber = 5
您会看到不允许更改常量的值。
如果 REPL 发出警告,提示您重新声明了现有常量或变量,这可能会有所帮助。
这是不允许的
不允许重新分配常量。
从 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
很酷,您甚至可以将一个值重新声明为不同的类型。
因为我们只有