Complete the code to declare a mutating method that changes the value of a property.
struct Counter {
var count = 0
mutating func increment() {
count [1] 1
}
}The increment method adds 1 to count using the += operator. This requires the method to be mutating because it changes the struct's property.
Complete the code to mark the method as mutating so it can modify the struct's property.
struct Point {
var x = 0, y = 0
[1] func moveBy(x deltaX: Int, y deltaY: Int) {
x += deltaX
y += deltaY
}
}The mutating keyword allows the method to change properties of the struct. Without it, the method cannot modify x and y.
Fix the error in the mutating method that tries to assign a new value to self.
struct Rectangle {
var width: Int
var height: Int
mutating func doubleSize() {
self [1] Rectangle(width: width * 2, height: height * 2)
}
}Assigning a new value to self inside a mutating method requires the assignment operator =. Using == is a comparison and causes an error.
Fill both blanks to create a mutating method that resets the point to origin.
struct Point {
var x: Int
var y: Int
[1] func reset() {
x [2] 0
y = 0
}
}The method must be marked mutating to change properties. To reset x, use the assignment operator = to set it to 0.
Fill all three blanks to create a mutating method that scales the size and updates the description.
struct Size {
var width: Int
var height: Int
var description: String
[1] func scale(by factor: Int) {
width [2] width * factor
height [3] height * factor
description = "Scaled size"
}
}The method must be mutating to change properties. To update width and height, assign the new scaled values using =. The description is updated by assignment.