Introduction
In Swift, whether you can change a collection depends on how you declare it. This helps keep your data safe and clear.
let collectionName = [item1, item2, item3] var collectionName = [item1, item2, item3]
let fruits = ["Apple", "Banana", "Cherry"] // fruits.append("Date") // Error: Cannot modify because fruits is a let constant
var fruits = ["Apple", "Banana", "Cherry"] fruits.append("Date") print(fruits)
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)
let, what does it mean for that collection?let in Swiftlet creates a constant, meaning the value cannot be changed after it is set.let, you cannot add, remove, or modify its elements because the collection itself is constant.let means constant collection [OK]var to declare variables that can change.var numbers = [1, 2, 3] correctly declares a mutable array. let is immutable, and const or mutable are not Swift keywords.let fruits = ["Apple", "Banana"]
fruits.append("Cherry")
print(fruits)fruits is declared with let, making it immutable.let numbers = [1, 2, 3] numbers[0] = 10 print(numbers)
numbers is declared with let, so it is immutable.var declares a mutable dictionary allowing adding or changing keys and values. let makes it immutable.Pass the test and this pattern moves unknown