Swift let vs var

How often you see a newbie programmer trying to learn new programming language and struggling with new keywords. One of those keywords are “var” and “let” .

In this post I’m going to concentrate on SWIFT LET VS WAR these two keywords “var” and “let” used in Swift Programming Language.

Variable: Variable is a name given to memory location.

Syntax: var variable name = value

Example: var name = “Nuclear Geeks”

When I say var name, so in the memory a new location is set up for storing the values and it is named as “name”. Hence variable is a name given to memory location.

So, I hope you are now comfortable with what variable is let us dig deep now on “difference between let and var”.

When you declare a variable with var, it means it can be updated, it is variable, it’s value can be modified.

When you declare a variable with let, it means it cannot be updated, it is non variable, it’s value cannot be modified.

Example:

var a = 1 
print (a) // output 1
a = 2
print (a) // output 2

let b = 4
print (b) // output 4
b = 5 // error "Cannot assign to value: 'b' is a 'let' constant"

Let us understand above example: We have created a new variable “a” with “var keyword” and assigned the value “1”. When I print “a” I get output as 1. Then I assign 2 to “var a” i.e I’m modifying value of variable “a”. I can do it without getting compiler error because I declared it as var.

In the second scenario I created a new variable “b” with “let keyword” and assigned the value “4”. When I print “b” I got 4 as output. Then I try to assign 5 to “let b” i.e. I’m trying to modify the “let” variable and I get compile time error “Cannot assign to value: ‘b’ is a ‘let’ constant”.

I hope it was as easy as pie, rather you would be feeling the same after reading this !! Do not forget to hit like button and shoot out your queries or questions in the comment section below.