在苹果的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 "这样的语句会抛出一个错误,因为常量不能被修改。

Let用于定义常量,var用于定义变量。 你使用var定义字符串,那么特定的string可以通过赋值给一个变量(在这种情况下它可以被修改)来修改(或突变),如果你使用let它是一个常量(在这种情况下它不能被修改):

var variableString = "Apple"
variableString += " and Banana"
// variableString is now "Apple and Banana"

let constantString = "Apple"
constantString += " and another Banana"
// this reports a compile-time error - a constant string cannot be modified

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

The

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

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

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

Let用于定义常量,var用于定义变量。

和C语言一样,Swift也使用变量来存储和引用变量的值。Swift还大量使用了值不可更改的变量。这些被称为常量,比c中的常量强大得多。当你处理不需要更改的值时,整个Swift都使用常量,使代码更安全、更清晰。 https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html