A mutating method may sound like something out of a mad scientist’s lab, but it’s actually how we change the properties of an instance using an instance method in Swift. So, we’ll need the mutating
keyword to do so:
struct Car {
var name : String ;
var speed : Int ;
init (name : String, speed : Int) {
self.name = name ;
self.speed = speed ;
}
// modify() is a mutating method:
mutating func modify() -> Int {
print("Car Modified") ;
self.speed += 40 ;
return self.speed ;
}
};
We added the mutating method modify()
to our Car
structure using the mutating
keyword. This method prints "Car Modified"
and can also affect self
(note how self.speed
can be increased). The method returns self.speed
at the end.
Take a look at what happens when we call the racingCar
: method on our Car
instance.
var racingCar = Car(name : "BMW i8", speed : 340) ;
var newSpeed = racingCar.modify() ;
// Prints: Car Modified
print(newSpeed) ; // Prints: 380
Our method worked as expected in the examples above:
Car Modified
was printed.racingCar.modify()
was successfully saved to newSpeed
.Car
increased by 40
, according to newSpeed
!If we tried to change a property using a regular method without the mutating
keyword, it would look like this:
func modify() -> Int {
print("Car Modified") ;
self.speed += 40 ;
return self.speed ;
}
Swift’s compiler would throw an error if you called racingCar.modify()
.
error: left side of mutating operator isn't mutable: 'self' is immutable
note: mark method 'mutating' to make 'self' mutable
This error indicates that we are unable to reassign a value to self
. So, the note goes on to say that we should use the mutating
keyword to let the method reassign self
.
Here are some useful tools to help you along your journey!
Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.