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

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

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

不能给属性赋值:'variableName'是一个'let'常量 将'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.

其他回答

在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

The

在Swift编程语言文档中,声明常量和变量部分指定了以下内容:

使用let关键字声明常量,使用var关键字声明变量。

确保理解Reference类型是如何工作的。与值类型不同,尽管引用类型的实例被声明为常量,但对象的底层属性可以改变。请参阅文档中的类是引用类型部分,并查看更改frameRate属性的示例。

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

非常简单:

设为常数。 Var是动态的。

描述一下:

创建一个常数。(有点像NSString)。一旦你设置了它,你就不能改变它的值。你仍然可以把它添加到其他东西,并创建新的变量。

Var创建一个变量。(有点像NSMutableString)所以你可以改变它的值。但这个问题已经被回答了好几次。

找到了一个很好的答案,希望能有所帮助:)