‘mutating’ in Swift


As we all know, Classes are reference type whereas Structures and Enumerations are of a value type in swift. What does that mean is that a class object shares a single instance of the object and passes the same reference if passed to any function or new object whereas the value type is the one which creates a copy of it and passes only the value.
If we try to change any variable inside a class it’s straight forward.
  
class Employee {
var name : String
var teamName : String

init(name: String, teamName: String) {
self.name = name
self.teamName = teamName
}

func changeTeam(newTeamName : String){
self.teamName = newTeamName
}
}

var emp1 = Employee(name : "Suneet", teamName:"Engineering")
print(emp1.teamName) //Engineering
emp1.changeTeam(newTeamName : "Product")
print(emp1.teamName) //Product
Whereas if you try to do the same in any value type, it will show us a compilation error,
  
struct Employee {
var name : String
var teamName : String

init(name: String, teamName: String) {
self.name = name
self.teamName = teamName
}

func changeTeam(newTeamName : String){
self.teamName = newTeamName
//cannot assign to property: 'self' is immutable
}
}
It will show us the below error
  
cannot assign to property: 'self' is immutable

It clearly states that adding mutating keyword to any function in value type can enable them to modify the variable. Internally when we try to mutate the value type, it does not mutate its value but it mutates the variable holding that value.
  
struct Employee {
var name : String
var teamName : String

init(name: String, teamName: String) {
self.name = name
self.teamName = teamName
}

mutating func changeTeam(newTeamName : String){
self.teamName = newTeamName
}

}

var emp1 = Employee(name : "Suneet", teamName:"Engineering")
print(emp1.teamName) //Engineering
emp1.changeTeam(newTeamName : "Product")
print(emp1.teamName) //Product
Not only enum or struct but there are other data types also which are of value type.
  • enum
  • struct
  • Int
  • Double
  • String
  • Array
  • Dictionary
  • Set
  • Tuple

Whereas the below ones of reference type
  • Functions
  • Closures
  • Class