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

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

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

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


当前回答

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

其他回答

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

例子:

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

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变量值可以改变,而let不能。如果你想让一个用户输入数据,你可以使用var来改变值,使用let数据类型变量来改变值。

var str      = "dog"  // str value is "dog"
str          = "cat"  // str value is now "cat"

let strAnimal = "dog" // strAnimal value is "dog"
strAnimal     = "cat" // Error !

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用于定义常量,var用于定义变量。

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