Recall & Review
beginner
What does the
mutating keyword do in Swift?It allows a method in a value type (like a struct or enum) to modify (change) the instance's properties.
Click to reveal answer
beginner
Why do value types need
mutating methods to change their properties?Because value types are copied when assigned or passed, Swift requires explicit permission (
mutating) to change their own data inside methods.Click to reveal answer
beginner
Can classes have
mutating methods in Swift?No. Classes are reference types and can always modify their properties inside methods without
mutating.Click to reveal answer
beginner
Example: What will this code print?
struct Counter {
var count = 0
mutating func increment() {
count += 1
}
}
var c = Counter()
c.increment()
print(c.count)It will print
1 because the increment() method changes the count property using mutating.Click to reveal answer
beginner
What happens if you remove
mutating from a method that changes a property in a struct?The Swift compiler will give an error because the method tries to change a property without permission to mutate the value type.
Click to reveal answer
What keyword must you add to a method in a struct to modify its properties?
✗ Incorrect
The
mutating keyword allows methods in value types like structs to modify their own properties.Which type requires
mutating methods to change properties?✗ Incorrect
Structs are value types and need
mutating methods to change their properties.What happens if you call a mutating method on a constant struct instance?
✗ Incorrect
You cannot call mutating methods on a struct instance declared with
let because it is immutable.Can enums have mutating methods in Swift?
✗ Incorrect
Enums can have mutating methods to change their current case value.
Why don't classes need the
mutating keyword?✗ Incorrect
Classes are reference types, so their methods can modify properties without
mutating.Explain why the
mutating keyword is necessary for methods in Swift structs.Think about how value types behave differently from classes.
You got /3 concepts.
Describe what happens if you try to modify a struct property inside a method without using
mutating.Consider Swift's safety rules for value types.
You got /3 concepts.