Mutating methods let you change the data inside value types like structs. Without them, value types cannot change their own properties.
Mutating methods for value types in Swift
struct MyStruct { var value: Int mutating func changeValue(newValue: Int) { value = newValue } }
The mutating keyword must be before the function name.
Only value types like struct and enum need mutating for methods that change properties.
struct Counter { var count = 0 mutating func increment() { count += 1 } }
struct Point { var x = 0, y = 0 mutating func moveBy(dx: Int, dy: Int) { x += dx y += dy } }
enum LightSwitch { case on, off mutating func toggle() { switch self { case .on: self = .off case .off: self = .on } } }
This program shows a bank account struct that can add or remove money using mutating methods. It prints the balance after each change and warns if there is not enough money.
struct BankAccount { var balance: Double mutating func deposit(amount: Double) { balance += amount } mutating func withdraw(amount: Double) { if amount <= balance { balance -= amount } else { print("Insufficient funds") } } } var myAccount = BankAccount(balance: 100.0) myAccount.deposit(amount: 50.0) print("Balance after deposit: \(myAccount.balance)") myAccount.withdraw(amount: 30.0) print("Balance after withdrawal: \(myAccount.balance)") myAccount.withdraw(amount: 150.0)
You cannot call mutating methods on constants (let) because they cannot change.
Mutating methods can also assign a new value to self to replace the whole instance.
Use mutating before methods that change properties in structs or enums.
Mutating methods let value types update their own data safely.
They cannot be used on constants because constants cannot change.
Practice
mutating keyword in Swift when used with methods inside a struct?Solution
Step 1: Understand the role of
In Swift, structs are value types and their properties cannot be changed inside instance methods unless the method is markedmutatingin structsmutating.Step 2: Effect of
Themutatingkeywordmutatingkeyword allows the method to modify the struct's properties safely.Final Answer:
It allows the method to modify properties of the struct. -> Option BQuick Check:
mutatinglets methods change struct data [OK]
- Thinking mutating makes method static
- Assuming mutating prevents changes
- Confusing mutating with access control
updateValue inside a struct in Swift?Solution
Step 1: Recall correct order of keywords in method declaration
In Swift, themutatingkeyword comes beforefuncwhen declaring a mutating method.Step 2: Match the syntax
mutating func updateValue() { } correctly showsmutating func updateValue() { }, which is the proper syntax.Final Answer:
mutating func updateValue() { } -> Option AQuick Check:
Keyword order: mutating before func [OK]
- Placing mutating after func
- Using 'mutate' instead of 'mutating'
- Adding mutating inside method body
struct Counter {
var count = 0
mutating func increment() {
count += 1
}
}
var myCounter = Counter()
myCounter.increment()
print(myCounter.count)What will be printed?
Solution
Step 1: Understand the mutating method effect
Theincrement()method is markedmutating, so it can increase thecountproperty by 1.Step 2: Trace the code execution
We createmyCounteras a variable instance, callincrement(), socountchanges from 0 to 1, then print outputs 1.Final Answer:
1 -> Option DQuick Check:
Mutating method changes count from 0 to 1 [OK]
- Expecting 0 because method looks like a function
- Thinking mutating methods cause errors always
- Using constant instance instead of variable
struct Point {
var x = 0
var y = 0
mutating func moveTo(newX: Int, newY: Int) {
x = newX
y = newY
}
}
let p = Point()
p.moveTo(newX: 10, newY: 20)What is the problem here?
Solution
Step 1: Identify instance mutability
The instancepis declared withlet, making it a constant.Step 2: Understand mutating method call on constant
Mutating methods cannot be called on constant instances because they change properties, which is not allowed.Final Answer:
Cannot call mutating method on a constant instance. -> Option CQuick Check:
Mutating methods need variable instances [OK]
- Thinking mutating keyword is missing
- Believing structs can't have mutating methods
- Assuming properties must be constants
BankAccount with a balance property. You need a mutating method deposit(amount:) that adds money to the balance only if the amount is positive. Which implementation correctly uses a mutating method to safely update the balance?Solution
Step 1: Check mutating method and property mutability
The method must be markedmutatingto changebalance, which must be a variable (var), not constant.Step 2: Verify correct logic for deposit
struct BankAccount { var balance: Double = 0 mutating func deposit(amount: Double) { if amount > 0 { balance += amount } } } addsamountonly if positive, correctly updatingbalance. struct BankAccount { var balance: Double = 0 func deposit(amount: Double) { if amount > 0 { balance += amount } } } lacksmutating, so it cannot changebalance. struct BankAccount { let balance: Double = 0 mutating func deposit(amount: Double) { balance += amount } } usesletfor balance, so it cannot be changed. struct BankAccount { var balance: Double = 0 mutating func deposit(amount: Double) { balance = amount } } replaces balance with amount without checking positivity.Final Answer:
struct BankAccount { var balance: Double = 0 mutating func deposit(amount: Double) { if amount > 0 { balance += amount } } } -> Option AQuick Check:
Mutating method + var property + condition = correct [OK]
- Forgetting mutating keyword
- Using let instead of var for properties
- Not checking if amount is positive
Ready to prove it?
Pass the test and this pattern moves unknown
