0
0
Swiftprogramming~10 mins

Weak references to break cycles in Swift - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Weak references to break cycles
Create Object A
Create Object B
A strong reference to B
B strong reference to A?
Strong reference cycle
Use weak reference in B to A
No cycle, objects deallocated
This flow shows how two objects referencing each other strongly cause a cycle, and how using a weak reference breaks it to allow deallocation.
Execution Sample
Swift
class Person {
  let name: String
  var apartment: Apartment?
  init(name: String) { self.name = name }
  deinit { print("Person \(name) is being deinitialized") }
}

class Apartment {
  let unit: String
  weak var tenant: Person?
  init(unit: String) { self.unit = unit }
  deinit { print("Apartment \(unit) is being deinitialized") }
}
Defines two classes where Apartment holds a weak reference to Person to avoid a strong reference cycle.
Execution Table
StepActionPerson instanceApartment instanceReference TypeOutput
1Create Person named AlicePerson(name: Alice)nilN/A
2Create Apartment unit 4APerson(name: Alice)Apartment(unit: 4A)N/A
3Set Alice.apartment = 4APerson(name: Alice) strong ref to Apartment(4A)Apartment(unit: 4A)Strong
4Set 4A.tenant = Alice (weak)Person(name: Alice)Apartment(unit: 4A) weak ref to Person(Alice)Weak
5Set Person and Apartment to nilnilnilN/APerson Alice is being deinitialized Apartment 4A is being deinitialized
6EndnilnilN/ABoth objects deallocated, no cycle
💡 Both Person and Apartment references are nil, weak reference prevents cycle, so deinit called.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5
personnilPerson(name: Alice)Person(name: Alice)Person(name: Alice)nil
apartmentnilApartment(unit: 4A)Apartment(unit: 4A)Apartment(unit: 4A)nil
person.apartmentnilnilApartment(unit: 4A)Apartment(unit: 4A)nil
apartment.tenantnilnilnilPerson(name: Alice) (weak)nil
Key Moments - 3 Insights
Why does using a strong reference from Apartment to Person cause a memory leak?
Because both Person and Apartment hold strong references to each other (see step 3), neither can be deallocated, causing a cycle. The execution_table shows no deinit output if both references are strong.
What does the 'weak' keyword do in the Apartment class?
It makes the reference to Person non-owning, so it doesn't increase the reference count. This allows Person to be deallocated when no other strong references exist, as shown by the deinit messages in step 5.
Why do we see deinitialization messages at step 5?
Because both person and apartment variables are set to nil, and the weak reference prevents a cycle, so both objects are freed and their deinit methods run, printing the messages.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 4. What type of reference does Apartment hold to Person?
AStrong reference
BWeak reference
CUnowned reference
DNo reference
💡 Hint
Check the 'Reference Type' column at step 4 in the execution_table.
At which step do both Person and Apartment get deallocated?
AStep 3
BStep 4
CStep 5
DStep 6
💡 Hint
Look at the 'Output' column for deinit messages in the execution_table.
If Apartment.tenant was a strong reference instead of weak, what would happen at step 5?
ANeither object deallocates (memory leak)
BBoth objects deallocate normally
COnly Person deallocates
DOnly Apartment deallocates
💡 Hint
Refer to the key_moments explanation about strong reference cycles causing memory leaks.
Concept Snapshot
Swift classes can create strong reference cycles when two objects hold strong references to each other.
Use 'weak' keyword to make one reference non-owning.
Weak references do not increase reference count.
This breaks cycles and allows ARC to deallocate objects.
Deinit methods confirm when objects are freed.
Full Transcript
This example shows two Swift classes, Person and Apartment, where Person has a strong reference to Apartment, and Apartment has a weak reference to Person. The flow starts by creating instances of both classes. Person's apartment property is set to the Apartment instance with a strong reference. Apartment's tenant property is set to the Person instance with a weak reference. This setup prevents a strong reference cycle. When both variables are set to nil, the weak reference allows ARC to deallocate both objects, confirmed by their deinit print statements. The execution table traces each step, showing how references change and when deinitialization occurs. Key moments clarify why weak references are needed to avoid memory leaks caused by cycles. The visual quiz tests understanding of reference types and deallocation timing. The snapshot summarizes the concept for quick recall.