0
0
Swiftprogramming~5 mins

Collection mutability tied to let/var in Swift

Choose your learning style9 modes available
Introduction
In Swift, whether you can change a collection depends on how you declare it. This helps keep your data safe and clear.
When you want a list of items that should never change after creation.
When you need to update or add items to a list during your program.
When you want to prevent accidental changes to your data.
When you want to clearly show which collections are fixed and which can change.
Syntax
Swift
let collectionName = [item1, item2, item3]
var collectionName = [item1, item2, item3]
let means the collection cannot be changed (immutable).
var means the collection can be changed (mutable).
Examples
This collection is declared with let, so you cannot add or remove items.
Swift
let fruits = ["Apple", "Banana", "Cherry"]
// fruits.append("Date") // Error: Cannot modify because fruits is a let constant
This collection is declared with var, so you can add new items.
Swift
var fruits = ["Apple", "Banana", "Cherry"]
fruits.append("Date")
print(fruits)
Sample Program
We create a mutable array colors and add "Blue" to it. Then we create an immutable array numbers and print it. Trying to add to numbers would cause an error.
Swift
var colors = ["Red", "Green"]
colors.append("Blue")
print(colors)

let numbers = [1, 2, 3]
// numbers.append(4) // This line would cause an error
print(numbers)
OutputSuccess
Important Notes
Trying to change a collection declared with let will cause a compile-time error.
You can change the contents of a collection declared with var anytime.
This rule helps prevent bugs by making your intentions clear in code.
Summary
Use let to make collections that cannot change.
Use var to make collections that you want to change.
This helps keep your data safe and your code easy to understand.