Strong reference cycles between classes in Swift - Time & Space Complexity
When two classes hold strong references to each other, it can cause a cycle that keeps them alive forever.
We want to understand how this cycle affects the program's behavior as objects increase.
Analyze the time complexity of the following code snippet.
class Person {
var name: String
var apartment: Apartment?
init(name: String) { self.name = name }
}
class Apartment {
var unit: String
var tenant: Person?
init(unit: String) { self.unit = unit }
}
let john = Person(name: "John")
let unit4A = Apartment(unit: "4A")
john.apartment = unit4A
unit4A.tenant = john
This code creates two classes that reference each other strongly, forming a cycle.
Look for loops or repeated calls that might grow with input size.
- Primary operation: There are no loops or recursion here.
- How many times: The references are set once each, so operations happen a fixed number of times.
Since there are no loops or repeated traversals, the operations do not grow with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Fixed number of reference assignments |
| 100 | Same fixed number of assignments |
| 1000 | Still the same fixed number |
Pattern observation: The work stays the same no matter how many objects you create here.
Time Complexity: O(1)
This means the time to set up these references does not grow with the number of objects.
[X] Wrong: "Because there is a cycle, the program will take longer as more objects are created."
[OK] Correct: The cycle affects memory management, not how many steps the program takes to set references.
Understanding how reference cycles affect program behavior helps you write safer code and explain memory management clearly.
"What if the classes had arrays of references to many objects instead of just one? How would the time complexity change?"