在苹果的Swift语言中,let和var有什么区别?

在我的理解中,它是一种编译语言,但它不在编译时检查类型。这让我很困惑。编译器如何知道类型错误?如果编译器不检查类型,这不是生产环境的问题吗?

当我试图给let赋值时给出了这个错误:

不能给属性赋值:'variableName'是一个'let'常量 将'let'改为'var'使其可变


当前回答

我在其他语言中遇到的常量的另一个区别是:不能为以后初始化常量(let),应该在你即将声明常量时初始化。

例如:

let constantValue : Int // Compile error - let declarations require an initialiser expression

变量

var variableValue : Int // No issues 

其他回答

Let用于定义常量,var用于定义变量。

和C语言一样,Swift也使用变量来存储和引用变量的值。Swift还大量使用了值不可更改的变量。这些被称为常量,比c中的常量强大得多。当你处理不需要更改的值时,整个Swift都使用常量,使代码更安全、更清晰。 https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html

在swift语言中,let是一个常量,意思是不能重新分配,但var可以重新分配

let question = "what is the difference between let and var?"

question = "another question" // this line cause syntax error

var answer = "let is constant and var is simple variable"

answer = "let can't be reassigned var can be reassigned" // this line will be excecuted

Let是一个常量,所以它永远不能改变。

let number = 5  
number = 6               //This will not compile.

Var是一个变量,可以更改(但在定义为不同的数据类型之后)。

var number = 5
number = 6               //This will compile.

如果您尝试将变量更改为不同的数据类型,它将不起作用

var number = 5
number = "Hello World"   //This will not compile.

简单的区别

Let =(不能更改)

Var =(随时更新)

Let是一个不可变变量,意思是它不能被改变,其他语言称它为常量。在c++中,你可以把它定义为const。

Var是一个可变变量,这意味着它可以被改变。在c++(2011版本更新)中,它与使用auto相同,尽管swift允许更大的灵活性。这是初学者更熟悉的变量类型。