Swift Mutability

Mutability (let vs var)

Use let for constants and var for variables.

Arrays and dictionaries declared with var can be modified in-place.


Mutable vs Immutable

Declare with var when you intend to add/remove elements; use let to prevent mutations.

Example

let fixed = [1, 2]
print(fixed.count)
var bag = [1, 2]
bag.append(3)
print(bag.count)


Dictionary Mutability

Mutate dictionaries declared with var by inserting or updating keys.

Example

var user = ["name": "Kai"]
user["city"] = "Oslo"
print(user.count)

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *