What is the difference between let
and var
in Apple\'s Swift language?
In my understanding, it is a compiled language but it does not check
Though currently I am still reading the manual, but I think this is very close to C/C++ const
pointer. In other words, something like difference between char const*
and char*
. Compiler also refuses to update content, not only reference reassignment (pointer).
For example, let's say you have this struct. Take care that this is a struct, not a class. AFAIK, classes don't have a concept of immutable state.
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
Because the structs are immutable by default, you need to mark a mutator method with mutating
. And because the name aaa1
is constant, you can't call any mutator method on it. This is exactly what we expected on C/C++ pointers.
I believe this is a mechanism to support a kind of const-correctness stuff.