Browse Questions
- These are SwiftUI's property wrappers for state management — each has a distinct ownership and lifecycle role.
- ARC is Swift's compile-time memory management system that automatically inserts retain and release calls to allocate and free class instances on the heap.
- These protocols define how types support equality checks, hashing, and ordering.
- A diffable data source is a data source that you drive with immutable snapshots of Hashable identifiers instead of index-path callbacks, and it computes the inserts, deletes, and moves for you.
Answer: ARC is Swift's compile-time memory management system that automatically inserts retain and release calls to allocate and free class instances on the heap.
Unlike garbage collection runtimes (such as Java or Go) which periodically pause execution to scan memory, ARC operates with zero runtime pause overhead by tracking reference counts deterministically:
- Reference Count Tracking: Every class instance maintains an internal reference count. When a strong reference is created, ARC calls
swift_retain(incrementing count); when a reference goes out of scope, ARC callsswift_release(decrementing count). When the count hits zero, the instance is immediately deallocated and itsdeinitis executed. - Side Tables: Swift optimizes memory by storing inline reference counts in the object's 64-bit header. When an object receives a
weakreference or its reference counts overflow, Swift allocates an external Side Table. The side table stores strong, unowned, and weak reference counts independently, enabling zeroing weak references without bloating instances that never use weak references. - Value Types vs Reference Types: Value types (
struct,enum, primitives) reside on the call stack or inline within containing types, requiring no reference counting. Only reference types (class, closures, actors) are managed by ARC on the heap.
Code Example:
class SessionManager {
let id: String
init(id: String) {
self.id = id
print("Session \(id) initialized")
}
deinit {
print("Session \(id) deallocated immediately when reference count reached 0")
}
}
func startSession() {
var ref1: SessionManager? = SessionManager(id: "AUTH_01") // retain count = 1
var ref2 = ref1 // retain count = 2
ref1 = nil // retain count = 1
ref2 = nil // retain count = 0 -> triggers deinit immediately
}
Key Points:
- ARC operates at compile time by inserting retain/release instructions into the Swift Intermediate Language (SIL)
- Stack allocation for value types is instant and requires no ARC overhead
- Side tables allow zeroing weak references without memory overhead for simple objects