Sobes.tech
Intern

What is the difference between var and let in Swift?

sobes.tech AI

Answer from AI

var declares a variable whose value can be changed. let declares a constant whose value cannot be changed after initialization.

// Declaring a variable - value can change
var mutableVariable = 10
mutableVariable = 20 // Ok

// Declaring a constant - value cannot change
let immutableConstant = 30
// immutableConstant = 40 // Error: Cannot assign to 'let' value

Using let is preferable when the value is guaranteed not to change, as it increases code safety and potentially allows the compiler to perform optimizations.

What is the difference between var and let in Swift… - sobes.tech