0
0
Swiftprogramming~5 mins

Adding methods in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Adding methods
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the array gets bigger, the method does more additions, one per number.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the method grows in a straight line with the input size.

Common Mistake

[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.

Interview Connect

Understanding how methods scale helps you explain your code clearly and shows you think about efficiency, a key skill in programming.

Self-Check

"What if the method used two separate loops over the array instead of one? How would the time complexity change?"