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

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

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

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


当前回答

简单的区别

Let =(不能更改)

Var =(随时更新)

其他回答

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关键字定义一个常量

let myNum = 7

所以myNum之后不能更改;

但是var定义了一个普通变量。

常量的值不需要在编译时知道,但是必须为它赋值一次。

你可以使用几乎任何你喜欢的字符作为常量和变量名,包括Unicode字符;

e.g.

var x = 7 // here x is instantiated with 7 
x = 99 // now x is 99 it means it has been changed.

但是如果我们采取let,那么……

let x = 7 // here also x is instantiated with 7 
x = 99 // this will a compile time error

在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关键字用于声明一个常量,var关键字用于声明一个变量。用这些引用、指针或值创建的变量。

它们之间的区别是,当你使用let创建一个变量时,它将在声明后成为常量,以后不能修改或重新赋值。相反,带有var的变量可以立即赋值,也可以稍后赋值,或者根本不赋值。在swift中,您必须非常明确地声明您所声明的内容。