In Swift, a mutating method is a function that can modify the properties of a struct or an enum. Structs and enums are value types in Swift, which means that when they are passed around, they are copied. Therefore, if we want to modify the properties of a struct or an enum, we need to use the mutating keyword to make it clear that this method changes the original value, not a copy of it.
For instance, consider the following struct:
struct Person {
var name: String
mutating func changeName(to newName: String) {
name = newName
}
}
In the above code, the struct Person
has a property name
, and a mutating method changeName(to:)
that takes a String
parameter newName
and changes the value of the name
property to newName
.
When we create a variable person
of type Person
, we can call the method changeName(to:)
to modify the value of the name
property:
var person = Person(name: "John")
person.changeName(to: "Mike")
After calling the changeName(to:)
method, the value of the name
property of the person
variable will be "Mike"
.
In summary, mutating methods in Swift structs allow us to modify the properties of a struct or an enum, and the use of the mutating keyword makes it clear that the method changes the original value, not a copy of it.
Asked: 2022-08-09 11:00:00 +0000
Seen: 16 times
Last updated: Nov 08 '22