0
0
Swiftprogramming~5 mins

Convenience initializers in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Convenience initializers
O(n)
Understanding Time Complexity

When using convenience initializers in Swift, it's helpful to know how the time to create an object changes as input grows.

We want to see how the number of steps to initialize an object scales with input size.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class NumberList {
    var numbers: [Int]

    init(numbers: [Int]) {
        self.numbers = numbers
    }

    convenience init(count: Int) {
        var temp = [Int]()
        for i in 1...count {
            temp.append(i)
        }
        self.init(numbers: temp)
    }
}
    

This code creates a list of numbers either from an existing array or by building one from 1 to count.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that appends numbers from 1 to count.
  • How many times: Exactly count times, once for each number.
How Execution Grows With Input

As the count grows, the loop runs more times, adding one number each time.

Input Size (count)Approx. Operations
1010 appends
100100 appends
10001000 appends

Pattern observation: The work grows directly with the input size; doubling count doubles the steps.

Final Time Complexity

Time Complexity: O(n)

This means the time to initialize grows linearly with the number of items you want to create.

Common Mistake

[X] Wrong: "Convenience initializers always run instantly regardless of input size."

[OK] Correct: Because if the initializer builds or processes data in a loop, the time depends on how much data it handles.

Interview Connect

Understanding how initializers scale helps you write efficient code and explain your design choices clearly in interviews.

Self-Check

"What if the convenience initializer used recursion instead of a loop? How would the time complexity change?"