0
0
Swiftprogramming~5 mins

Classes are reference types in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Classes are reference types
O(1)
Understanding Time Complexity

When working with classes in Swift, it's important to understand how operations on them grow as the program runs.

We want to see how the time to copy or assign class instances changes as we work with more objects.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Person {
    var name: String
    init(name: String) {
        self.name = name
    }
}

var person1 = Person(name: "Alice")
var person2 = person1
person2.name = "Bob"

This code creates a class instance and assigns it to another variable, then changes a property.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Assigning a reference from one variable to another.
  • How many times: Happens once here, no loops or repeated traversals.
How Execution Grows With Input

Since assignment copies only the reference, the time does not grow with the number of objects.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The operation takes the same time regardless of how many objects exist.

Final Time Complexity

Time Complexity: O(1)

This means assigning or copying a class instance reference takes the same small amount of time no matter how many objects there are.

Common Mistake

[X] Wrong: "Copying a class variable duplicates the whole object and takes longer with bigger objects."

[OK] Correct: Actually, copying a class variable just copies the reference, not the whole object, so it takes constant time.

Interview Connect

Understanding how classes work as references helps you explain memory use and performance clearly, a useful skill in many coding discussions.

Self-Check

"What if we changed the class to a struct? How would the time complexity of copying change?"