gpt4 book ai didi

swift - let 和 var 在 Swift REPL 中对 const 的重新声明无效

转载 作者:可可西里 更新时间:2023-11-01 00:56:51 26 4
gpt4 key购买 nike

在 Swift REPL 中,我可以使用 let 分配常量,但为什么我可以稍后使用 var 修改它?

let name = "al"

var name = "bob"

Swift 在这里并没有提示,但 name 不是常量吗?

最佳答案

在 Swift 中重新声明一个变量(在同一范围内)是无效的:

$ cat test.swift let name = "al"var name = "bob"$ swiftc test.swift test.swift:2:5: error: invalid redeclaration of 'name'var name = "bob"    ^test.swift:1:5: note: 'name' previously declared herelet name = "al"    ^

但是,Swift REPL 的行为不同:

$ swiftWelcome to Apple Swift version 3.1 (swiftlang-802.0.53 clang-802.0.42). Type :help for assistance.  1> let name = "al" name: String = "al"  2> var name = "bob"name: String = "bob"

这是故意的,正如在 Redefining Everything with the Swift REPL :

... but in the REPL interactive environment it’s useful to be able to easily make changes. The REPL was specifically designed with this kind of convenience in mind ...

... The newer definition replaces the existing definition for all subsequent references


注意:您必须单独输入行。如果您复制这些行将两行放入粘贴缓冲区,启动 REPL 并粘贴他们用 CmdV 然后结果是

$ swiftWelcome to Apple Swift version 3.1 (swiftlang-802.0.53 clang-802.0.42). Type :help for assistance.  1> let name = "al"   2. var name = "bob"error: repl.swift:2:5: error: invalid redeclaration of 'name'var name = "bob"    ^

显然这两个语句现在在同一范围内进行评估(第二行有继续提示)并产生错误。同样的情况发生在一行中的两个语句中:

$ swiftWelcome to Apple Swift version 3.1 (swiftlang-802.0.53 clang-802.0.42). Type :help for assistance.  1> let name = "al" ; var name = "bob"error: repl.swift:1:23: error: invalid redeclaration of 'name'let name = "al" ; var name = "bob"                      ^

关于swift - let 和 var 在 Swift REPL 中对 const 的重新声明无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45262283/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com