577 views
What is the difference between var and let in Swift?
AI answer
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.
Similar questions
- What is the difference between variable declarations using var and let in JavaScript?
- What are the differences between value types and reference types in Swift?
- What are the limitations associated with using lazy let in Swift?
- What is the difference between a set and a dictionary in Swift?
- What are the differences between data structures in Swift and Objective-C?