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

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

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

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


当前回答

关键字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 

其他回答

Let用于不能修改的常量,而var是普通变量

例子:

let name = " Bob " 像name = " Jim "这样的语句会抛出一个错误,因为常量不能被修改。

在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 maximumNumberOfLoginAttempts = 10 var currentLoginAttempt = 0   
let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0

在一行中声明多个常量或多个变量,用逗号分隔:

var x = 0.0, y = 0.0, z = 0.0

打印常量和变量

你可以用println函数输出常量或变量的当前值:

println(friendlyWelcome)

Swift使用字符串插值将常量或变量的名称作为占位符包含在更长的字符串中

将名称用括号括起来,并在开括号前用反斜杠转义:

println("The current value of friendlyWelcome is \(friendlyWelcome)")

参考资料:http://iosswift.com.au/?p=17

用可变性/不可变性概念来陈述这种差异可能更好,这是对象空间中值和实例可变性的正确范式,比唯一的“常量/变量”通常概念更大。 而且这更接近于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编程语言书

和C语言一样,Swift使用变量来存储和引用值 识别的名字。Swift还大量使用了变量whose 数值不可修改。这些被称为常数,而且很多 比C语言中的常量更强大。

var和let都是引用,因此let是const引用。 使用基本类型并不能真正说明let与const有何不同。 区别在于当它与类实例(引用类型)一起使用时:

class CTest
{
    var str : String = ""
}

let letTest = CTest()
letTest.str = "test" // OK

letTest.str = "another test" // Still OK

//letTest = CTest() // Error

var varTest1 = CTest()
var varTest2 = CTest()
var varTest3 = CTest()

varTest1.str = "var 1"
varTest2.str = "var 2"
varTest3 = varTest1
varTest1.str = "var 3"

varTest3.str // "var 3"