Mutating methods for value types in Swift - Time & Space Complexity
We want to understand how the time it takes to run mutating methods on value types changes as the data size grows.
How does changing a value type's data inside a method affect the work done?
Analyze the time complexity of the following code snippet.
struct Counter {
var counts: [Int]
mutating func incrementAll() {
for i in counts.indices {
counts[i] += 1
}
}
}
var counter = Counter(counts: [1, 2, 3, 4, 5])
counter.incrementAll()
This code defines a value type with an array and a mutating method that increases each number by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array to increment each element.
- How many times: Once for each element in the array.
As the array gets bigger, the method does more work because it updates every element.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 increments |
| 100 | 100 increments |
| 1000 | 1000 increments |
Pattern observation: The work grows directly with the number of elements; doubling elements doubles the work.
Time Complexity: O(n)
This means the time to run the mutating method grows in a straight line with the size of the array.
[X] Wrong: "Mutating a value type is always slow because it copies the whole data every time."
[OK] Correct: Swift uses copy-on-write optimization, so the actual work depends on what the method changes, not copying everything each time.
Understanding how mutating methods work helps you explain how your code handles data changes efficiently, a useful skill in many coding discussions.
"What if the mutating method only changed one element instead of all? How would the time complexity 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
