0
0
Swiftprogramming~5 mins

Mutating methods for value types in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Aoverride
Bstatic
Cfinal
Dmutating
Which type requires mutating methods to change properties?
AStruct
BProtocol
CClass
DEnum without cases
What happens if you call a mutating method on a constant struct instance?
AThe struct becomes mutable
BIt works normally
CCompiler error: cannot use mutating method on let constant
DThe method is ignored
Can enums have mutating methods in Swift?
AOnly in classes
BYes, to change their cases
COnly if they have raw values
DNo, enums are immutable
Why don't classes need the mutating keyword?
ABecause classes are reference types and can always modify their properties
BBecause classes cannot change properties
CBecause classes are immutable
DBecause classes use <code>final</code> instead
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.