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

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

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

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


当前回答

在var的情况下,值可以被重新赋值

 //Variables
 var age = 42
 println(age) //Will print 42
 age = 90
 println(age) //Will Print 90

** newAge常量不能被重新赋给一个新值。尝试这样做会给出一个编译时错误**

//Constants
let newAge = 92 //Declaring a constant using let
println(newAge) //Will print 92.

其他回答

Let用于声明一个常量值-在给出初始值后,您将不会更改它。 Var用于声明一个变量值—您可以根据需要更改它的值。

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

在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

关键字var用来定义一个变量,你可以像这样轻松地修改它的值:

var no1 = 1 // declaring the variable 
no1 = 2 // changing the value since it is defined as a variable not a constant

但是,let关键字仅用于创建一个常量,当您不想再次更改常量的值时使用。如果你试图改变常数的值,你会得到一个错误:

let no2 = 5 // declaring no2 as a constant
no2 = 8 // this will give an error as you cannot change the value of a constant 

Var是唯一的方法来创建一个变量在swift。Var并不像javascript这样的解释性语言那样意味着动态变量。例如,

var name = "Bob"

在本例中,变量名称的类型推断为name类型为String,例如,我们也可以通过显式定义type来创建变量

var age:Int = 20

现在如果你将一个字符串赋值给age,编译器就会给出错误。

Let用于声明常量。例如

let city = "Kathmandu"

或者我们也可以,

let city:String = "Kathmandu"

如果您试图更改city的值,则会在编译时给出错误。