What is ARC (Automatic Reference Counting) in Swift?

Answer

ARC (Automatic Reference Counting) is Swift's memory management system for class instances (reference types). It automatically tracks the number of strong references to each class instance and deallocates the instance when the count reaches zero. How it works: when you create a class instance, ARC allocates memory and sets count = 1. Every new strong reference increments the count. When a reference goes out of scope, ARC decrements the count. When count = 0, the deinitializer runs and memory is freed. Strong reference (default): class Person { var name: String init(name: String) { self.name = name } deinit { print("\(name) deallocated") } } var alice: Person? = Person(name: "Alice") // count = 1 var ref2: Person? = alice // count = 2 alice = nil // count = 1 ref2 = nil // count = 0 -- "Alice deallocated". Retain cycle problem: two objects strongly reference each other — count never reaches zero — memory leak: class Node { var next: Node? // Strong -- can cause cycle }. Weak references (weak var): don't increment count, automatically set to nil when the referenced object is deallocated: class Parent { var child: Child? } class Child { weak var parent: Parent? // Breaks cycle }. Unowned references (unowned): like weak but never become nil — use when the referenced object always outlives the reference: class Owner { let card: CreditCard } class CreditCard { unowned let owner: Owner // Card always has owner }. Always use weak/unowned in closures to prevent retain cycles: { [weak self] in self?.doWork() }.