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.

This post was originally posted at https://agrawalsuneet.github.io/blogs/mutating-in-swift/ and reposted on Medium on 29th Mar 2019.

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

Please continue reading at https://agrawalsuneet.github.io/blogs/mutating-in-swift/

That’s all for now. You can read my other interesting posts here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.