Adding methods in Swift - Time & Space Complexity
When we add methods to a class or struct, we want to know how the time to run those methods changes as input grows.
We ask: How does the work inside these methods scale with bigger inputs?
Analyze the time complexity of the following code snippet.
struct Numbers {
var values: [Int]
func sum() -> Int {
var total = 0
for number in values {
total += number
}
return total
}
}
This code defines a method sum() that adds all numbers in an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the array.
- How many times: Once for every element in the array.
As the array gets bigger, the method does more additions, one per number.
| 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.
Time Complexity: O(n)
This means the time to run the method grows in a straight line with the input size.
[X] Wrong: "Adding a method does not affect time complexity because it's just a function."
[OK] Correct: The method's code can have loops or other operations that grow with input size, so it does affect time complexity.
Understanding how methods scale helps you explain your code clearly and shows you think about efficiency, a key skill in programming.
"What if the method used two separate loops over the array instead of one? How would the time complexity change?"
Practice
What is the main purpose of adding methods to a struct or class in Swift?
Solution
Step 1: Understand what methods do
Methods are functions inside a struct or class that perform actions related to that type's data.Step 2: Identify the purpose of methods
Methods organize code by grouping behaviors with the data they act on, making code reusable and clear.Final Answer:
To add actions or behaviors related to the data inside the type -> Option DQuick Check:
Methods = actions on data [OK]
- Thinking methods only store data
- Confusing methods with properties
- Believing methods change the type itself
Which of the following is the correct way to define a method named greet inside a Swift struct?
struct Person {
// Your method here
}Solution
Step 1: Recall Swift method syntax
In Swift, methods inside structs or classes use the keywordfuncfollowed by the method name and parentheses.Step 2: Check each option
func greet() { print("Hello") }usesfunc greet(), which is correct. The other options use incorrect keywords not valid in Swift.Final Answer:
func greet() { print("Hello") } -> Option CQuick Check:
Swift methods start with func [OK]
- Using 'method', 'def', or 'function' instead of 'func'
- Missing parentheses after method name
- Not placing method inside struct or class
What will be the output of the following Swift code?
struct Counter {
var count = 0
mutating func increment() {
count += 1
}
}
var c = Counter()
c.increment()
print(c.count)Solution
Step 1: Understand the struct and method
The struct has a variablecountstarting at 0. The methodincrementadds 1 tocount. It is markedmutatingto allow changing the struct's data.Step 2: Trace the code execution
We createcas a Counter instance withcount = 0. Callingc.increment()increasescountto 1. Printingc.countoutputs 1.Final Answer:
1 -> Option AQuick Check:
Mutating method changes count from 0 to 1 [OK]
- Forgetting 'mutating' keyword causes error
- Expecting count to stay 0 after increment
- Confusing structs with classes (no mutating needed)
Identify the error in this Swift code and choose the fix:
struct BankAccount {
var balance: Double = 0.0
func deposit(amount: Double) {
balance += amount
}
}Solution
Step 1: Understand the error cause
The methoddeposittries to changebalance, a property of the struct. In Swift, methods that modify struct properties must be markedmutating.Step 2: Identify the fix
Addingmutatingbeforefunc depositallows the method to modifybalance. Other options do not fix the mutation error.Final Answer:
Addmutatingbeforefunc deposit-> Option AQuick Check:
Mutating keyword needed to change struct properties [OK]
- Omitting 'mutating' keyword causes compile error
- Changing var to let prevents modification
- Misusing static keyword for instance methods
You want to add a method reset() to this Swift struct that sets count back to zero. Which is the correct way to do this?
struct Counter {
var count: Int
// Add reset method here
}Solution
Step 1: Understand method purpose and struct rules
The methodreset()must change the propertycount. SinceCounteris a struct, methods that modify properties must be markedmutating.Step 2: Evaluate options
mutating func reset() { count = 0 }correctly usesmutating func reset()and setscount = 0.func reset() { count = 0 }lacksmutating, causing error.static func reset() { count = 0 }is static and cannot access instance property.func reset() -> Int { return 0 }returns 0 but does not changecount.Final Answer:
mutating func reset() { count = 0 } -> Option BQuick Check:
Mutating method needed to reset struct property [OK]
- Forgetting 'mutating' keyword causes error
- Using static method cannot access instance data
- Returning value instead of changing property
Ready to prove it?
Pass the test and this pattern moves unknown
