Swift Value Types, Dynamic Dispatch, and ARC
Problem Explain classes vs structs in Swift including how classes are maintained internally, dynamic dispatch, Automatic Reference Counting, and reference cycles.
Be ready to discuss
- Classes are reference types: heap-allocated, shared by pointer, support inheritance and deinitializers, and identity is comparable with
===. - Structs are value types: copied on assignment, stack-allocated where the compiler can manage it, no inheritance, with copy-on-write behind the standard library collections.
- Why value semantics are the Swift default: no aliasing means no spooky action at a distance, and thread safety comes almost for free.
- Dynamic dispatch: class methods dispatch through a vtable,
@objc/dynamicmembers go through the Objective-C message send, and protocol requirements dispatch via a witness table. - Static dispatch and devirtualisation:
final,private, and whole-module optimization let the compiler bypass the vtable entirely. - ARC: the compiler inserts retain/release calls to track strong reference counts, and the instance deallocates the moment the count hits zero - deterministic, unlike a tracing GC.
- Reference cycles: two objects holding strong references to each other never reach zero, so both leak; closures capturing
selfstrongly are the most common real-world case. - Breaking cycles:
weak(optional, auto-nils on dealloc) vsunowned(non-optional, crashes if accessed after dealloc), capture lists like[weak self], and why delegates are conventionallyweak var.
asked …