Skip to Content
Learn
Structures
Mutating Methods

While a mutating method may sound like a term out of a mad scientist’s lab, it’s actually how we change an instance’s properties using an instance method. To do so, we need the mutating keyword:

struct Dog { var age : Int var isGood : Bool init(age: Int, isGood: Bool) { self.age = age self.isGood = isGood } // birthday() is a mutating method: mutating func birthday() -> Int { print("Best doggy") self.age += 1 return self.age } }

In our Dog structure, we used the mutating keyword to add the mutating method birthday(). This method prints out "Best doggy", is also able to affect self — note how we can increment self.age. In the end, the method returns self.age.

Let’s take a look at when we call the method on our Dog instance, bucket:

var bucket = Dog(age: 7, isGood: true) var newAge = bucket.birthday() // Prints: Best doggy print(newAge) // Prints: 8

Above, our method worked as expected:

  • Best doggy printed out.
  • We were able to save the return value of bucket.birthday() to newAge.
  • Printing out newAge showed that bucket‘s age increased by 1!

If we tried to use a regular method to change a property, without the mutating keyword, like so:

func birthday() -> Int { print("Best doggy") self.age += 1 return self.age }

Calling bucket.birthday() Swift’s compiler would raise an error.

error: left side of mutating operator isn't mutable: 'self' is immutable
note: mark method 'mutating' to make 'self' mutable

This error lets us know that we can’t reassign a value for self. The note then tells us to use the mutating keyword to allow the method to reassign self.

Instructions

1.

In the Band structure, let’s create the basis of our mutating method:

  • the mutating method should be called changeGenre() and it has a single parameter newGenre: String and returns a String.
  • Inside the method body, return an empty string "".
2.

Now to fill in the body of the method. Inside the body of changeGenre():

  • Assign self.genre as newGenre.
  • Return self.genre instead of "".
3.

Under the declaration of journey, create a variable named bandsNewGenre call .changeGenre() on journey with the argument newGenre: "rock".

Then print out bandsNewGenre to see the changed value.

Folder Icon

Take this course for free

Already have an account?