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

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

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

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

其他回答

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的情况下,值可以被重新赋值

 //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.

用可变性/不可变性概念来陈述这种差异可能更好,这是对象空间中值和实例可变性的正确范式,比唯一的“常量/变量”通常概念更大。 而且这更接近于Objective C的方法。

2 .数据类型:值类型和引用类型。

在值类型的上下文中:

'let'定义一个常量(不可变)。'var'定义了一个可变值(mutable)。

let aInt = 1   //< aInt is not changeable

var aInt = 1   //< aInt can be changed

在参考类型中:

数据的标签不是值,而是对值的引用。

if Person = Person(名称:Foo,第一个:Bar)

person不包含此人的数据,但包含此人数据的引用。

let aPerson = Person(name:Foo, first:Bar)
               //< data of aPerson are changeable, not the reference

var aPerson = Person(name:Foo, first:Bar)
               //< both reference and data are changeable.

eg:

var aPersonA = Person(name:A, first: a)
var aPersonB = Person(name:B, first: b)

aPersonA = aPersonB

aPersonA now refers to Person(name:B, first: b)

and

let aPersonA = Person(name:A, first: a)
let aPersonB = Person(name:B, first: b)

let aPersonA = aPersonB // won't compile

but

let aPersonA = Person(name:A, first: a)

aPersonA.name = "B" // will 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

尽管你已经得到了let和var之间的许多区别,但一个主要的区别是:

let is compiled fast in comparison to var.