0
0
Swiftprogramming~5 mins

Initializers and designated init in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Initializers and designated init
O(n)
Understanding Time Complexity

When we create objects in Swift, initializers set up their starting state. Understanding how long this setup takes helps us write faster programs.

We want to know how the time to create an object changes as we add more properties or complexity.

Scenario Under Consideration

Analyze the time complexity of the following initializer code.


class Person {
    var name: String
    var age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}
    

This code sets up a Person object with a name and age using a designated initializer.

Identify Repeating Operations

Look for repeated steps or loops in the initializer.

  • Primary operation: Assigning values to properties.
  • How many times: Each property is assigned once per object creation.
How Execution Grows With Input

As we add more properties, the number of assignments grows.

Input Size (number of properties)Approx. Operations
22 assignments
1010 assignments
100100 assignments

Pattern observation: The time grows directly with the number of properties to set.

Final Time Complexity

Time Complexity: O(n)

This means the time to initialize grows linearly with the number of properties.

Common Mistake

[X] Wrong: "Initializers always take the same time no matter how many properties there are."

[OK] Correct: Each property needs to be set, so more properties mean more work and more time.

Interview Connect

Understanding how initializers work and their time cost shows you know how object setup affects performance, a useful skill in many coding tasks.

Self-Check

"What if the initializer called another initializer inside it? How would that affect the time complexity?"