let和var在Swift REPL中无效的const重声明 [英] let and var Invalid redeclaration of const in Swift REPL

查看:111
本文介绍了let和var在Swift REPL中无效的const重声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift REPL中,我可以使用 let 分配一个常量,但是为什么以后可以使用 var 对其进行修改?

In Swift REPL I can assign a constant with let, but why can I modify it later using var?

let name = "al"

var name = "bob"

Swift在这里没有抱怨,但是不是常量吗?

Swift is not complaining here, but wasn't name a constant?

推荐答案

在Swift中重新声明变量(在相同范围内)无效:

Redeclaring a variable (in the same scope) is not valid in 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 here
let name = "al"
    ^

但是,Swift REPL的行为有所不同:

However, the Swift REPL behaves differently:


$ swift
Welcome 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"

这是有意的,如
使用Swift REPL重新定义一切


...但是在REPL交互式环境中,能够轻松进行更改。 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并将
Cmd V 粘贴在一起,然后结果是


Note: You have to enter the lines separately. If you copy those two lines into the paste buffer, start the REPL and paste them with CmdV then the result is


$ swift
Welcome 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"
    ^

显然,这两个语句现在在相同的作用域
中求值(第二行有一个继续提示)并产生错误。
这两个语句都在同一行中发生相同的情况:

Apparently the two statements are now evaluated in the same scope (the second line has a continuation prompt) and produce an error. The same happens with both statements in a single line:


$ swift
Welcome 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"
                      ^

这篇关于let和var在Swift REPL中无效的const重声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆