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

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

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

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


当前回答

虽然目前我还在阅读手册,但我认为这非常接近C/ c++的const指针。换句话说,类似于char const*和char*之间的区别。编译器也拒绝更新内容,不仅是引用重赋(指针)。

例如,假设你有这样一个结构体。注意,这是一个结构,而不是一个类。AFAIK,类没有不可变状态的概念。

import Foundation


struct
AAA
{
    var inner_value1    =   111

    mutating func
    mutatingMethod1()
    {
        inner_value1    =   222
    }
}


let aaa1    =   AAA()
aaa1.mutatingMethod1()      // compile error
aaa1.inner_value1 = 444     // compile error

var aaa2    =   AAA()
aaa2.mutatingMethod1()      // OK
aaa2.inner_value1 = 444     // OK

因为结构在默认情况下是不可变的,所以需要用mutating标记mutator方法。因为名字aaa1是常量,你不能对它调用任何mutator方法。这正是我们在C/ c++指针上所期望的。

我相信这是一种支持常量正确性的机制。

其他回答

Let是一个不可变变量,意思是它不能被改变,其他语言称它为常量。在c++中,你可以把它定义为const。

Var是一个可变变量,这意味着它可以被改变。在c++(2011版本更新)中,它与使用auto相同,尽管swift允许更大的灵活性。这是初学者更熟悉的变量类型。

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.

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

例子:

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

我在其他语言中遇到的常量的另一个区别是:不能为以后初始化常量(let),应该在你即将声明常量时初始化。

例如:

let constantValue : Int // Compile error - let declarations require an initialiser expression

变量

var variableValue : Int // No issues 

在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