Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between `let` and `var` in Swift?

Tags:

swift

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 the type at compile time. It makes me confused. How does the compiler know about the type error? If the compiler doesn't check the type, isn't it a problem with production environment?

This error is given when I try to assign a value to a let:

Cannot assign to property: 'variableName' is a 'let' constant
Change 'let' to 'var' to make it mutable

like image 698
Edward Avatar asked Jun 02 '14 19:06

Edward


People also ask

What is the difference between VAR and let?

let is block-scoped. var is function scoped. let does not allow to redeclare variables. var allows to redeclare variables.

Which is better let or VAR?

This is because both instances are treated as different variables since they have different scopes. This fact makes let a better choice than var . When using let , you don't have to bother if you have used a name for a variable before as a variable exists only within its scope.

Why let is used in Swift?

Swift employs the keywords let and var for naming variables. The let keyword declares a constant, meaning that it cannot be re-assigned after it's been created (though its variable properties can be altered later). The var keyword declares a new variable, meaning that the value it holds can be changed at a later time.

What does VAR mean in Swift?

In swift, we use the var keyword to declare a variable. Swift uses variables to store and refer to values by identifying their name.


1 Answers

The let keyword defines a constant:

let theAnswer = 42 

The theAnswer cannot be changed afterwards. This is why anything weak can't be written using let. They need to change during runtime and you must be using var instead.

The var defines an ordinary variable.

What is interesting:

The value of a constant doesn’t need to be known at compile time, but you must assign the value exactly once.

Another strange feature:

You can use almost any character you like for constant and variable names, including Unicode characters:

let 🐶🐮 = "dogcow" 

Excerpts From: Apple Inc. “The Swift Programming Language.” iBooks. https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewBook?id=881256329


Community Wiki

Because comments are asking for adding other facts to the answer, converting this to community wiki answer. Feel free edit the answer to make it better.

like image 104
10 revs, 8 users 70% Avatar answered Sep 23 '22 06:09

10 revs, 8 users 70%