Immutability as: “not capable of or susceptible to change” and mutability as “capable of change or of being changed”.
To rephrase immutable means can’t be changed and mutable means can be changed.
In swift code, we apply the concepts of immutability and mutability using the keywords let and var respectively.
for more detail visit this link it has detail description with code
Mutable variables
// Declaration and assignment of a mutable variable name.
var name = "Kory"
// Reassignment or mutation of the variable name.
name = "Ryan"
Above we declared a variable named “name” and assigned its value to be the String literal “Kory”. On line five we reassigned the variable to be the String literal “Ryan”.
This is an example of a mutable variable. Using the keyword var allows us to change the value the variable holds. The variable “name” can be changed to whatever String we like.
Mutable variables are needed when the value of a variable is expected to change. Let’s take a look at a slightly more complicated example.
// Declares a new type Person
struct Person {
var name: String
var age: Int
}
// Creates an instance of person named kory.
var kory = Person(name: "Kory", age: 30)
// Mutates Kory's properties
kory.age = 31
kory.name = "Scooby"
In the above example both the name and age properties of instance of a Person are mutable, they can be changed. In this example mutability is important. A person’s name or age can and will change in real life. Having mutable variables allows our data too closely resemble the real world thing we are trying to model.
Immutable contants
Often the words variable and constants are used interchangeably but there is a subtle difference. Mutability. Variables as the name implies can vary with the data they hold. Constants cannot and are therefore are immutable and in other words constant. Swift allows us to represent an immutable constant with the keyword “let”. Consider the below example.
// Declaration and assignment of a mutable variable name.
let name = "Kory"
name = "Ryan" // Cannot assign to property: 'name' is a 'let' constant
The above example is nearly identical to the mutable example but will not compile. When an identifier such as “name” is set to be immutable with the keyword “let” it cannot be changed once assigned. You can delay assignment as illustrated below. But you cannot change name once it has been assigned.
let name: String
// Some important code here
name = "Kory"
You can also use constants inside of structs and classes when you want to make one or more properties immutable even if the instance is declared as mutable.
// Declares a new type Person with constants properties
struct Person {
age name: String
let age: Int
}
var kory = Person(name: "Kory", age: 30)
kory.name = "Ryan"
kory.age = 30 // Cannot assign to property: 'age' is a 'let' constant
Even though kory is declared with var, internally age is declared with let and cannot be mutated. Mutating name is fine.