Methods in structs in Swift - Time & Space Complexity
When we use methods inside structs, it's important to know how the time to run them changes as the data grows.
We want to find out how the method's work grows when the input changes.
Analyze the time complexity of the following code snippet.
struct NumberList {
var numbers: [Int]
func sum() -> Int {
var total = 0
for num in numbers {
total += num
}
return total
}
}
This code defines a struct with a method that adds up all numbers in an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that goes through each number in the array.
- How many times: Once for each number in the array.
As the list gets bigger, the method takes longer because it adds more numbers.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items; double the items, double the work.
Time Complexity: O(n)
This means the method takes longer in a straight line as the list gets bigger.
[X] Wrong: "The method runs in the same time no matter how many numbers there are."
[OK] Correct: Because the method adds each number one by one, more numbers mean more work and more time.
Understanding how methods inside structs work with data size helps you explain your code clearly and shows you know how performance changes with input.
"What if the method sorted the numbers before adding them? How would the time complexity change?"
Practice
What is the main purpose of a method inside a Swift struct?
Solution
Step 1: Understand what methods do in structs
Methods are functions inside structs that define behaviors or actions the struct can perform.Step 2: Differentiate methods from data storage
Properties store data, while methods perform actions using that data.Final Answer:
To define actions the struct can perform -> Option AQuick Check:
Methods = actions in structs [OK]
- Confusing methods with properties
- Thinking methods create new types
- Mixing methods with import statements
Which keyword must be used before a method in a Swift struct if it changes the struct's properties?
Solution
Step 1: Recall Swift's rule for modifying struct properties
Struct methods that change properties must be marked withmutatingto allow modification.Step 2: Identify the correct keyword
Among the options, onlymutatingenables property changes inside struct methods.Final Answer:
mutating -> Option DQuick Check:
Change properties = mutating [OK]
- Using override in structs (only for classes)
- Confusing static with mutating
- Omitting mutating keyword causes errors
What will be the output of this Swift code?
struct Counter {
var count = 0
mutating func increment() {
count += 1
}
}
var myCounter = Counter()
myCounter.increment()
print(myCounter.count)Solution
Step 1: Understand the mutating method increment()
The method increases count by 1 and is marked mutating, so it can change the property.Step 2: Trace the code execution
myCounter starts with count = 0, increment() adds 1, so count becomes 1, then printed.Final Answer:
1 -> Option BQuick Check:
mutating method changes count to 1 [OK]
- Forgetting mutating causes error
- Expecting count to stay 0
- Thinking print outputs nil
Identify the error in this Swift struct method and how to fix it:
struct Score {
var points = 0
func addPoint() {
points += 1
}
}Solution
Step 1: Check if method modifies a property
addPoint() tries to increase points by 1, which modifies the struct's property.Step 2: Recall Swift rule for modifying properties in structs
Methods that modify properties must be markedmutating, otherwise compiler error occurs.Final Answer:
Method must be markedmutatingto changepoints-> Option CQuick Check:
Modify property in struct method = mutating needed [OK]
- Omitting mutating keyword
- Changing var to let (makes property immutable)
- Thinking method must return value
Given this struct, which method correctly resets the level property to 1?
struct Game {
var level = 5
// Which method resets level to 1?
}Solution
Step 1: Identify method that changes a property
Resetting level means changing the property, so method must be mutating.Step 2: Check each option
A lacks mutating, so cannot modify property. B is mutating but only returns 1 without changing level. C is static and cannot access instance property. D is mutating and correctly sets level to 1.Final Answer:
mutating func reset() { level = 1 } -> Option AQuick Check:
Change property in struct method = mutating func [OK]
- Forgetting mutating keyword
- Using static func to access instance properties
- Returning value instead of changing property
Ready to prove it?
Pass the test and this pattern moves unknown
