Debug School

rakesh kumar
rakesh kumar

Posted on

Difference between let and var in swift

let (Constant)
var (Variable)
Memory Concept
With Objects
Best Practice

Interview Questions

Can a let value be modified
Can a let class object change its properties?
Can a let struct change its properties?

let (Constant)

Once a value is assigned, it cannot be changed.

let name = "Ashwani"

print(name)

Output:

Ashwani

Trying to modify it:

let name = "Ashwani"

name = "Raj"

Output:

Cannot assign to value: 'name' is a 'let' constant
Enter fullscreen mode Exit fullscreen mode

var (Variable)

A var value can be changed anytime.

var age = 25

age = 26

print(age)

Output

26
Example
let company = "Apple"

var employee = "John"

employee = "Mike"

// company = "Google" ❌ Error

print(company)
print(employee)

Output

Apple
Mike
Enter fullscreen mode Exit fullscreen mode

Memory Concept

let

let pi = 3.14159
pi
 │
 ▼
3.14159

Cannot change
Enter fullscreen mode Exit fullscreen mode

var

var score = 10

score = 20
Initially

score
 │
 ▼
10

After update

score
 │
 ▼
Enter fullscreen mode Exit fullscreen mode

20

With Objects

let Object

class Person {
    var name = "John"
}

let p = Person()

p.name = "Mike"

This is allowed because let makes the reference constant, not the object's internal properties.

p ─────────► Person
               │
               ▼
            name = Mike

But this is not allowed:

p = Person()

Error:

Cannot assign to value: 'p' is a 'let' constant
Enter fullscreen mode Exit fullscreen mode

var Object

var p = Person()

p = Person()

This is allowed because the reference itself can change.
Enter fullscreen mode Exit fullscreen mode

With Structs

Structs are value types.

struct Student {
    var name: String
}

let s = Student(name: "Ashwani")

s.name = "Raj"

Output

Cannot assign to property: 's' is a 'let' constant
Enter fullscreen mode Exit fullscreen mode

Since the entire struct is constant, none of its properties can change.

Using var:

var s = Student(name: "Ashwani")

s.name = "Raj"

print(s.name)

Output

Raj
Enter fullscreen mode Exit fullscreen mode

Best Practice

Swift encourages using let by default and switching to var only when a value truly needs to change.

// Good
let country = "India"

// Good
var counter = 0
counter += 1
Enter fullscreen mode Exit fullscreen mode

Interview Questions

Q1. Can a let value be modified?

Answer: No. Once initialized, its value cannot change.

Q2. Can a let class object change its properties?

Answer: Yes, if those properties are declared with var. The object reference is constant, but the object's mutable properties can still change.

Q3. Can a let struct change its properties?

Answer: No. Since structs are value types, declaring a struct with let makes the entire instance immutable.

Top comments (0)