What is the difference between let and var in Swift?

Answer

In Swift, let declares a constant and var declares a variable. let name = "Alice" // Constant -- cannot be changed name = "Bob" // Error: cannot assign to value: 'name' is a 'let' constant var age = 30 // Variable age = 31 // Fine. Why prefer let? Swift encourages immutability. Constants: enable compiler optimizations, document intent (this value won't change), prevent accidental mutation, required for thread safety. Use var only when the value genuinely needs to change. Value types vs reference types with let: For value types (struct, enum), let makes the entire value immutable: let point = CGPoint(x: 0, y: 0) point.x = 5 // Error. For reference types (class), let makes the reference constant but the object can still mutate: let person = Person() person.name = "Alice" // OK -- changing object, not reference person = Person() // Error -- can't reassign the reference. Collections: let array = [1, 2, 3]; array.append(4) // Error var array2 = [1, 2, 3]; array2.append(4) // Fine. Xcode warns when a var is never mutated — should be let.