Swift & Concurrency (50 Qs)•Part 1: Core Language, Memory & Value Types (1 - 10)
What is a Retain Cycle (Strong Reference Cycle) and how do you resolve it?
junior LevelCode ExampleswiftCore Language
In Simple Words: A retain cycle occurs when two class instances hold strong references to each other, preventing either reference count from ever reaching 0:
- Result: Memory Leak; neither instance can ever be deallocated!
- Resolution: Break the cycle using
weakorunownedreferences:weak: Does not increment reference count. Must be anOptional(weak var parent: Person?). Automatically becomesnilwhen the referenced instance is deallocated.unowned: Does not increment reference count. Non-optional; expects the referenced instance to never becomenilduring its lifetime (crashes if accessed after deallocation).
swift
class Order {
var customer: Customer?
}
class Customer {
// FIX: Declare as weak to break retain cycle!
weak var activeOrder: Order?
}