Skip to main content
InterviewHubPRO
Section Overview
Q3

Question 3 of 50

Part 1: Core Language, Memory & Value Types (1 - 10)

6%
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 weak or unowned references:
    • weak: Does not increment reference count. Must be an Optional (weak var parent: Person?). Automatically becomes nil when the referenced instance is deallocated.
    • unowned: Does not increment reference count. Non-optional; expects the referenced instance to never become nil during 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?
}