Classes are reference types in Swift - Time & Space 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.
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 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.
Since assignment copies only the reference, the time does not grow with the number of objects.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The operation takes the same time regardless of how many objects exist.
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.
[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.
Understanding how classes work as references helps you explain memory use and performance clearly, a useful skill in many coding discussions.
"What if we changed the class to a struct? How would the time complexity of copying change?"