在苹果的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用于定义常量,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 number = 5  
number = 6               //This will not compile.

Var是一个变量,可以更改(但在定义为不同的数据类型之后)。

var number = 5
number = 6               //This will compile.

如果您尝试将变量更改为不同的数据类型,它将不起作用

var number = 5
number = "Hello World"   //This will not compile.

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

Var值可以改变,初始化后。但让价值不被改变,当它被初始化一次。

在var情况下

  function variable() {
     var number = 5, number = 6;
     console.log(number); // return console value is 6
   }
   variable();

如果让

   function abc() {
      let number = 5, number = 6;
      console.log(number); // TypeError: redeclaration of let number
   }
   abc();

在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