0
0
Swiftprogramming~5 mins

Adding initializers via extension in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Adding initializers via extension
O(n)
Understanding Time Complexity

When we add initializers using extensions in Swift, it is important to understand how this affects the time it takes to create objects.

We want to know how the time to initialize grows as we create more instances.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


struct Point {
    var x: Int
    var y: Int
}

extension Point {
    init(value: Int) {
        self.x = value
        self.y = value
    }
}

let points = (1...n).map { Point(value: $0) }
    

This code adds a new initializer to the Point struct using an extension, then creates an array of Points using that initializer.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Creating each Point instance using the new initializer.
  • How many times: The initializer runs once for each number from 1 to n.
How Execution Grows With Input

Each new Point is created one after another, so the total time grows directly with how many Points we make.

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

Pattern observation: The time increases evenly as we add more Points.

Final Time Complexity

Time Complexity: O(n)

This means the time to create all Points grows in a straight line with the number of Points.

Common Mistake

[X] Wrong: "Adding an initializer via extension makes object creation slower in a way that grows faster than the number of objects."

[OK] Correct: The initializer code runs once per object, so the total time grows directly with the number of objects, not faster.

Interview Connect

Understanding how adding initializers affects creation time helps you explain how your code scales when making many objects, a useful skill in real projects.

Self-Check

"What if the initializer did some extra work like looping inside it? How would the time complexity change?"